C language learning notes (beginner) (from zero to function)

Introduction to C language

C language is a process oriented and abstract general programming language, which is widely used in the bottom development. C language has the characteristics of high efficiency, flexibility, rich functions, strong expression and high portability. It is favored in program design. C language compiler generally exists in various operating systems, such as Microsoft Windows, macOS, Linux, Unix and so on. The design of C language influenced many later programming languages, such as C + +, Objective-C, Java, c# and so on.

C language grammatical structure

Let's take a look at the simplest program:

#include<stdio.h> 
int main()//int indicates the type of the return value of the function, and main is the function name
{
    printf("Hello World");//printf() is an output function, which can be equivalent to fprintf(stdout,"Hello world")
/*Each C language statement must be added at the end; number.*/
    return 0; //Function return value
}

This code contains a basic program structure
Where #include < stdio h> Is to introduce a header file, which contains the declaration of some functions written in c language. In other words, it is the declaration made by using functions written by others Class is equivalent to the import library name in python
It should also be noted that there are some differences in some syntax in different C language versions For example, in vc2010, the code can also be written as

#include<stdio.h>
void main(){

	printf("Hello world");

}

In addition, in C language, the runtime will only execute the contents of the main function. Only when calling other functions within the main function will it jump to other functions to run relevant code

C language format input and output

(first of all, a very important point is that in C language, all hardware, such as keyboard and mouse, are regarded as file objects for C language. This is particularly important in later file operations.)
I Output function
printf("Hello world") outputs a string here
Next, use a case to illustrate;

#include<stdio.h>
void main(){
	int a=3;
	float b=3.0f;
	double c=3.0;
	char *str="Hello"//Point to a string through the string pointer. Here you only need to know that str is a string
	char d='a';
	printf("a=%d,b=%f,c=%f,str=%s,d=%c",a,b,c,str,d);
}

II Input function scanf()
The core of this function is format. Here is an example;

#include<stdio.h>
void main(){
	char a;//Create a character variable a
	char str[100];//Create a character array to store strings
	scanf("a=%c,str=%s",&a,str);
	/*scanf()The function writes the value to the memory corresponding to the variable, so you need to use the address symbol, such as & A,
	However, for an array, it is passed in the form of address, so there is no need to add*/
	printf("a=%c,str=%s",a,str);
	
}

Next is the key point. The input of the program must be a=a,b=hello

The reason is

scanf("a=%c,str=%s",&a,str);
If you change scanf ("% C,% s", & A, STR);
You must enter:
a,hello

C language variable naming

There's nothing to say about naming. The point is not to bring strange operators and strictly case sensitive

int a
float b
double c
Type in front and variable name in the back. Don't forget to separate; number.

After that, C language will open up corresponding space in memory

C language data type

1. Basic data type
2. Construction data type
3. Pointer type
4. There are four categories of empty types
In the basic data types of C language, each data has a clear allocation of space size (in the same compilation environment)
Take a code as an example:

#include<stdio.h>
void main(){
	float a;//Define an integer variable named a
	printf("a The memory occupied is%d byte",sizeof(a));

}

It should be noted here that in older versions of C language, the defined code is executed first, and then the corresponding code operations are executed, such as

#include<stdio.h>
void main(){
	float a;//Define an integer variable named a
	printf("a The memory occupied is%d byte",sizeof(a));
	int b;//It's wrong to define another b, but it's OK in the latest version

}

This happens later in memory

If we are defining an int b; It will open up a space with two bytes
Therefore, a problem is introduced here. When only two bytes of data are required to be stored in four bytes, it should be no problem, but there will be a problem when four bytes are stored in two bytes of space Therefore, we can draw a conclusion that the data with less memory can be transferred into the large memory space, but the large can not be stored into the small. If it is to be transferred, some data must be lost This is the automatic conversion and coercion of C language

Here is a piece of code (automatic conversion)

#include<stdio.h>
void main(){
	float a;
	int b=3;
	a=b;
	printf("a=%f,b=%d",a,b);
}


Now let's turn it around

#include<stdio.h>
void main(){
	float a=3.00;
	int b;
	b=a;
	printf("a=%f,b=%d",a,b);
}

We can find that he sends out a warning (the warning is not an error and can run in the end, but the consequences are at your own risk)

So the question is, how to cast
Just change the code as follows

b=(int)a

Another thing to note here is
Suppose there are three variables a, B and C
b=(int)a + c
Not equivalent to b= int (a+c)

The following data types will be explained in detail in the following blog. The following is the name and scope of use of the basic data structure Subject to vc2010

Operation priority and operator

Look at a table first

Arithmetic operators such as addition, subtraction, multiplication and division > size and relational operators > logical operators (excluding!) > Conditional operator > assignment operator > comma operator
What is priority? To put it bluntly, it means whether to add and subtract first or multiply and divide later This is how an operation is calculated, which is similar to mathematics For example, if you multiply first and then add, the priority of multiplication is higher than that of addition
Then there are some chestnuts
(in C language, 0 is false and non-zero is true)
Here is the difference between a + + and + + A. suppose associate (a=3) is the former, and the return result is 3. At this time, a is 4 The latter will return the self - added result 4 For example, b=a++,c=++a, the result is b=3,c=4

#include<stdio.h>
void main(){
	int a=1;
	int b=3;
	int c;
	printf("%d\n",!(a>b));//(a > b) return to 0,! Returns a non-zero result of 1;
	printf("%d\n",-(b++));//Equivalence and - (b + +)
	printf("%d",!a&&b>5);//The result is zero
}

The next thing I want to talk about is the more important bit operation and ternary operation in C language
Binocular operation
expression? a:b;
for instance

#include<stdio.h>
void main(){
	int a=1;
	int b=3;
	int c;
	c=a>b?a:b;
	printf("c=%d",c);//The result is three. A > b is false. All return the second value B, that is, 3. On the contrary, C = a < B? a:b; Returns the first value a
}

Bit operation
This may not be very friendly. Just try to understand I will list the more common rules
Let's talk about the operation symbols first: &, |, ^ (or), < (left shift), > > (right shift).
Then there is the original code, inverse code and complement code
For a positive number with three codes in one, for a negative number, it should be converted to complement first and then to complement, and then use complement operation
Here is an example;
Original code:
A representation in which a sign is added directly before a value For 8-bit binary:
(+ 7) original = 00000000 00000111
(- 7) original = 10000000 00000111
Inverse code:
The inverse code of a positive number is the same as the original code
The inverse code of a negative number, the sign bit is "1", and the numerical part is reversed by bit
(+ 7) inverse = 00000000 00000111
(- 7) inverse = 10000000 01111000
Complement:
The complement of a positive number is the same as the original code
The complement of negative numbers is that the sign bit is "1", and the value part is reversed by bit, and then 1 is added to the last bit (lowest bit) That is "inverse code + 1"
(+ 7) supplement = 00000000 00000111
(- 7) supplement = 10000000 01111001

The above is the storage of a number in the memory, so the next step is the operation
0&0=0
0&1=0
1&1=0

0|0=0
0|1=1
1|1=1

0^0=0
0^1=1
1^1=0

Here are some examples

Move left and right


About this, remember a formula > > division, < < multiply and then take an integer, multiply and divide by 2 (remember it's an integer)
int a=10;
int b=10;
Printf ("% d", a > > 1) / / the result is 5
Equivalent to
b=a/2;
printf("%d",b)
I.e. a > > b
Equivalent to int c;
c=a/(b*2)

Code block in C language

Let's take a look at the initial program. We find that they are enclosed by a pair of curly braces. This pair of curly braces is a code block, and the memory space of each code block is relatively independent for instance;

#include<stdio.h>
void main(){
	int a=3;
	int a=4;
	printf("a=%d",a);
	//A redefined error will be raised
}


But this:

#include<stdio.h>
void main(){
	int a=3;
	{
	int a=4;
	printf("a=%d\n",a);
	}
	printf("a=%d",a);
	//A redefined error will be raised
}


For specific reasons, we can see the following memory distribution diagram

When executing the previous code, we mainly see the stack area

Here's a distinction

	int a=3;
	{
		a=4;
	}
	printf("a=%d",a);
	//No load creates a new a, and the result is 4

Conditional statement

The code block is mentioned above, and the condition is simple below
if()

if()
{there are multiple statements}
else()
{there are multiple statements}

if()
{there are multiple statements}
else if()
{there are multiple statements}
else()
{there are multiple statements}
Here are some examples:
I if statement

if (condition)
{
	//code
}
else
{
	//code
}
#include<stdio.h>
void main(){
	int year;
	scanf("%d",&year)
	int Februaryx;//February of leap year
	if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))
	{//There is only one statement, and the curly braces can be removed
		Februaryx = 29;
	}
	else
	{
		Februaryx = 28;
	}
	printf("%d\n", Februaryx);
}

There are more coquettish, judging students' grades

#include<stdio.h>
void main(){
	int score;
	printf("Enter the student's grade\n");
	//fprintf(stdout, "enter student's grade \ n");
	scanf("%d",&score);
	
	if (score == 100)
	{
		printf("A\n");
	}
	else
	{
		if (score >= 90)
		{
			printf("B\n");
		}
		else
		{
			if (score >= 80)
			{
				printf("C\n");
			}
			else
			{
				if (score >= 70)
				{
					printf("D\n");
				}
				else
				{
					if (score >= 60)
					{
						printf("E\n");
					}
					else
					{
						printf("F\n");
					}
				}
			}
		}
	}

}
//There is no need to pay attention to indentation in C language, and each statement is used; Just separate it (I mainly write too much in python)

switch Statements

Look at the code above and you'll see that sometimes conditional statements don't look good So a new thing called switch switch statement is introduced here

switch (variable or expression)
{
case value 1:
{
//Processing content
break;
}
case value 2:
{
//Processing content
break;
}
default
{
//Processing content
break;
}
}
Variables here can be of various types, but in general, int and char are used more often

The following is a section of code, pay attention to the comments;
(judge how many days there are in a month, except February of leap year)

#include<stdio.h>
void main(){

int month;

int day;
scanf("%d",month);
switch (month)
{
	case 1:	
	{
		day = 31;
		printf("This month%d day",day);
		break;
	}
	case 2:
	{
		day = 28;
		printf("This month%d day",day);
		break;
	}
	case 3:
	{
		day = 31;
		printf("This month%d day",day);
		break;/*End the whole statement. If there is no break statement, the execution will continue when month=3 until the end of the whole statement
		That is, 31,30,31666 will be output


	*/
	}
	case 4:	
	{
		day = 30;
		printf("This month%d day",day);
		break;
	}		
	case 5:		
		day = 31;
		printf("This month%d day",day);
		break;
	}
	default:	//Other situations
	{
		day = 666;
		printf("This month%d day",day);
		break;
	}
}

}

loop

There are three cycles in language
For (initialization variable; execution condition; variable change) {}
While (execution condition) {}

Do {} while (execution condition);
(the most special thing I think is this. There is one behind others; then execute first and then judge)
Here are some examples;

#include<stdio.h>

void main() {
	int i; 
	for(i=0;i<10;i++){
		printf("I think bloggers are handsome:\n");
		printf("Number of consent%d\n",i);
	}
//Finally, i=10, run for ten times
	printf("%d",i);//Value of output i
}


Its execution order is equivalent to

void main() {
	int i=0; 
	for(;i<10;){
		printf("I think bloggers are handsome:\n");
		printf("Number of consent%d\n",i);
		i++;
	}
//Finally, i=10, run for ten times
	printf("%d",i);//Value of output i
}

Similarly, while loop

#include<stdio.h>
int main() {
    int i=0;
    while(i<10){
        printf("I think bloggers are handsome:\n");
		printf("Number of consent%d\n",i);
        i++;
	} 
}

do while loop

#include<stdio.h>
void main() {
    int i=0;
    do{
        printf("I think bloggers are handsome:\n");
		printf("Number of consent%d\n",i);
        i++;
      } while(i<10);
}

function

There's a lot to be said about function. If you go far, you have to pull the function pointer I won't write so much in the introductory chapter
First, the position of the function, where time is in front (in front of the main function)
for instance

void print (int i){//The return value of the function is null, and int i is a formal parameter

	printf("I think bloggers are handsome:\n");
	printf("Number of consent%d\n",i);

}
/*The first point is that the user-defined function should not have the same name as the system function. The second point indicates the return type. Only one main function is allowed in a C language project*/
#include<stdio.h>
void main() {
    int i=0;
    do{
		print(i);
        i++;
      } while(i<10);
	printf("%d",i);
}

If it is later, it must be stated
For example:

/*The first point is that the user-defined function should not have the same name as the system function. The second point indicates the return type. Only one main function is allowed in a C language project*/
#include<stdio.h>
void main() {
	void print (int i);//Declaration function, in fact, this is also the content of a header file
    int i=0;
    do{
		print(i);
        i++;
      } while(i<10);
	printf("%d",i);
}

void print (int i){//The return value of the function is null, and int i is a formal parameter

	printf("I think bloggers are handsome:\n");
	printf("Number of consent%d\n",i);

}

Header file

When it comes to functions, the header file will be discarded without talking about it
This thing is prepared to better manage the functions written by yourself

Now, let's put the function we wrote earlier into a file



This is the final code

#include"print_myself.h" / * import custom header files. This method can also be used to import system header files
 Only relatively speaking<>Better import effect*/
#include<stdio.h>
void main() {
    int i=0;
    do{
		print(i);
        i++;
      } while(i<10);
	printf("%d",i);
	getchar();
}

There are pointer, array, structure, common body and basic file operation behind C language The introduction is still very simple. It feels as difficult as python, but it is not so concise. However, for large-scale projects, the readability of C language is really fragrant Here I want to express my point of view. Some people always say that C language is difficult and Python is simple. In fact, generally speaking, it depends on what direction is suitable. From the perspective of syntax structure, the difficulty of the two is almost the same, but from other directions, such as using Python as UI interface and comparing with C language, the results are obvious However, this is only from the perspective of language ontology, not from other development directions Of course, this is just my personal opinion. Different people have different opinions. Don't spray if you don't like it

Tags: C

Posted by LightningSt on Sun, 08 May 2022 23:45:25 +0300