Introduction to computer C language must see and review the simple knowledge points of C language

Keywords: C Back-end

Introduction to computer C language must see and review the simple knowledge points of C language

@
Tip: after the article is written, the directory can be generated automatically. Please refer to the help document on the right for how to generate it

preface

How to enter the computer industry starts with this article.

1. Why learn c language

The reason is very simple: C language is the ancestor of most high-level languages. Learning C language and learning other languages get twice the result with half the effort. C language is the parent language and the bridge between human-computer interaction and the bottom.

In the IT industry, there is usually a change every 10 years. In recent 50 years, C/C + + has occupied the top three places in the TIOBE ranking list for a long time without any shaking. It can be said to be classic and never out of date!

Therefore, as a computer student, C language is a must.

2. Compiler selection

Here I recommend using vs2019 (integrated development environment) as the compiler for daily learning

In Colleges and universities, students are often recommended to use dev c + +. I always use vs2019. After using dev c + +, I can only say that vs is like modern people, and dev c + + is like the ancients =. = dev c + + is far from smooth and easy to use as vs2019.

The following is the installation tutorial of vs2019. You can try to install it here.

[vs2019 installation tutorial]( Installation and simple use of VS2019 - visual studio 2019 installation tutorial beep beep bilibili bili)

3. What is c language

C language is a general computer programming language, which is widely used in underlying development. The design goal of C language is to provide a programming language that can compile and process low-level memory in a simple way, generate a small amount of machine code and run without any running environment support. Although C language provides many low-level processing functions, it still maintains a good cross platform The C language program written in a standard specification can be compiled on many computer platforms, even including some embedded processors (single chip microcomputer or MCU) And supercomputers and other operating platforms. In the 1980s, in order to avoid differences in C language syntax used by various developers, the US National Bureau of standards developed a complete set of American national standard syntax for C language, called ANSI C, as the initial standard of C language. [1] at present, on December 8, 2011, the international organization for Standardization (ISO) and the International Electrotechnical Commission (IEC) The published C11 standard is the third official standard of C language and the latest standard of C language. The standard better supports Chinese character function name and Chinese character identifier, and realizes Chinese character programming to a certain extent. C language is a process oriented computer programming language.

It can be simply understood as a low-level language. For example, windows system is made in c/c + + language

4. The first c language program

#include<stdio.h>
int main()
{
    printf("hello world!");
    return 0;
}

Almost every student played helloworld when he first learned, but why did he play like this?

Let's understand the meaning of each symbol one by one!

#include is the header file, including instructions. stdio.h is the header file

Note that the header file here contains the stdio.h * * header file to be included with * * < >.

. h is the suffix of the header file. Each header file has * *. H * * at the end.

Main is a function. In c language, this function is used as the entry of c program. A c language program has and only has one main function (remember)

The content in {...} is our code.

What is printf? Printf is a printing function.

His header file is stdio.h, which is why we include header files. Printf cannot be used for header files that do not contain printf.

The format used by the printf function is ("what needs to be printed").

return 0; indicates the end of the function.

5.c language data type

char / / character data type

Short / / short integer

int / / shaping

Long / / long integer

long long / / longer shaping

float / / single precision floating point number

Double / / double precision floating point number

Why do we need so many data types?

In our daily life, we only use the language composed of numbers and symbols

char provides the data type of characters

int, double and other data types provide integer data types and floating-point data types that can meet various requirements of numbers.

Use of data types

#include<stdio.h>
int main()
{
    char ch = "w";   // Ch is the name and w is the content stored in the ch
    int b = 10;     // b is the name and 10 is the stored content of b, that is, b = 10
    double a = 20;    //ditto
    return 0; 
}

What is the size of each data type?

Learn about the c language keyword sizeof (note that it is not a function)

sizeof is an operator that obtains the length of an object (data type or data object) (that is, the size of memory occupied, in byte s).

Conversion of computer units under Popularization

bit is the smallest unit of a computer

8 bit = 1 byte

1024 byte = 1 kb

1024 kb = 1mb

1024mb = 1gb

...

It can be seen that the unit of the result of sizeof operation is bytes

#include <stdio.h>
int main()
{    
    printf("%d\n", sizeof(char));    
    printf("%d\n", sizeof(short));    
    printf("%d\n", sizeof(int));    
    printf("%d\n", sizeof(long));    
    printf("%d\n", sizeof(long long));    
    printf("%d\n", sizeof(float));    
    printf("%d\n", sizeof(double));    
    printf("%d\n", sizeof(long double));
    return 0;
}

You can see the size of each data type. It is worth exploring why long and int are 4?

In fact, the size of long > = the size of int.

!! c language has no string data type

6. Variable, constant

variable

Define variables
#include<stdio.h>
int main()
{
    int age = 0;//Define a variable of type int and initialize the value of the variable to 0;
    int age;    //Define a variable of type int, but it is not initialized. It stores random values
    char ch = "w";  //Define a variable of char type and initialize it to the character "w"
    
    return 0;
}

For example, when defining a variable, you need to determine the data type for the variable

Classification of variables

Variables are divided into

  • global variable

  • local variable

    #include<stdio.h>
    int a = 100;//Define global variables
    int main()
    {
        int b = 2;//Define local variable b
        int a = 10;//Define local variable a
            printf("%d",a);
    }
    

    You can try whether an error will be reported when the global variable and local variable names are the same in your compiler

    If there is no error, what is the printed result

The result is obviously 10.

Here we can draw two conclusions

  • There is no problem with the definition of local variables and global variables above.

  • When the local variable has the same name as the global variable, the local variable takes precedence.

Use of variables

Variables are used to store values.

So how do we assign the value we want to a variable?

Next, we introduce the scanf function (format input function)

scanf function is a standard library function, and its function prototype is in the header file "stdio.h".

The general form of scanf function is: scanf("format control string", address table column);

%d is used to accept the values of a and b after input. It is worth noting that, unlike the printf function, when scanf function receives the values of a and b, it needs to add & (take the address symbol) before a and b. only in this way can the input of shaping a and b be completed

Extension:

  • %d indicates that its output format is decimal signed integer.
  • %f indicates that its output format is floating point number.
  • %lf is the same as% f, indicating floating point number. However, it is used in the input function scanf, and% f is used in the output function printf.
  • %c indicates that the output format is character.
  • %s indicates that its output format is string.
Scope and life cycle of variables

What does scope and lifecycle mean?

  • Scope, a programming concept. Generally speaking, the name used in a piece of program code is not always valid / available, and the scope of the code that limits the availability of the name is the scope of the name.
  • The life cycle of a variable refers to the period between the creation of a variable and its destruction

Next, use code to understand their syntax

You can see that the local variable i can be used in the mian function, but not in the test function.

This involves the knowledge of the scope and life cycle of local variables in c language

  • . the scope of a local variable is the local scope of the variable.

    At the same time, after the local variable is created, it will be automatically destroyed after the code block is created. obtain:

  • The life cycle of a local variable is the beginning of the scope life cycle and the end of the scope life cycle.

Global variables can be used in both test function and main function without error

obtain:

  • The scope of the global variable is the whole project.

  • The life cycle of global variables is the life cycle of the whole program.

This involves the knowledge of the scope and life cycle of local variables in c language

  • . the scope of a local variable is the local scope of the variable.

    At the same time, after the local variable is created, it will be automatically destroyed after the code block is created. obtain:

  • The life cycle of a local variable is the beginning of the scope life cycle and the end of the scope life cycle.

[external chain picture transferring... (img-g4LWVQFB-1635483271198)]

Global variables can be used in both test function and main function without error

obtain:

  • The scope of the global variable is the whole project.

  • The life cycle of global variables is the life cycle of the whole program.

    constant

Constants in C language are divided into the following types:

  • Literal constant

  • const modified constant

  • #Identifier constant defined by define

  • enumeration constant

Understanding several constants in code

#include<stdio.h>
int main()
{
    3.14;//Literal constant
    1000;//Literal constant
    const float a = 1.28f;  //const modified constant
    //a = 1000;  // error; Constant cannot change size.
    #define MAX 100;    //define modified constant
    return 0;
}

Special attention should be paid here:


When defining an array, the array size is a constant, but the constant a modified by const cannot be placed in the array, and an error will be reported.

The reason is that although const modified variables have the attribute of constants, they are still variables in nature. They are generally called const modified constant variables. There are both constant attributes and variable attributes.

7. String + escape character

character string
"helloworld!"

This string of characters enclosed by double quotes is called String Literal, or simply word

Character string.

Note: the end flag of the string is an escape character of \ 0. When calculating the string length, \ 0 is the end flag and is not counted as the string content.

#include<stdio.h>
int main()
{
    char arr1[] = "bit";
    char arr2[] = { 'b','i','t','\0' };
    char arr3[] = { 'b','i','t' };
    printf("%s\n", arr1);
    printf("%s\n", arr2);
    printf("%s\n", arr3);
    return 0;
}

By code and result

We can clearly see that since there is no \ 0 in arr3, the final result of the array is not bit, but a pile of garbled code after bit,

The reason is that the end flag of the string array is \ 0. Because the \ 0 after bit is not detected during printing, the program will print the following characters until it meets \ 0.

Escape character

Introduced by a problem

Print a directory: c:\code\test.c

General idea:

#include<stdio.h>
int main()
{
	printf("c:\code\test.c\n");
	return 0;
}

Operation results:

The reason behind this printing failure is: the pot of escape characters.

Let's learn about escape characters

? Used when writing consecutive question marks to prevent them from being parsed into three letter words

\'used to represent character constants'

\"" is used to represent the double quotation marks inside a string

\Used to represent a backslash to prevent it from being interpreted as an escape sequence character.

\a warning character, beep

\b backspace

\f feed character

\n line feed

\r enter

\t horizontal tab

\v vertical tab

\DD represents 1 ~ 3 octal digits. For example: \ 130 X

8 \ XDDD represents 2 hexadecimal digits. For example: \ x30

Escape characters exist to make the compiler run better.

How do I print c:\code\test.c next

#include<stdio.h>
int main()
{
	printf("c:\\code\\test.c\n");
	return 0;
}

That's it.

Content of popular notes
         C++Style notes

          //   xxxxxxxx

          You can annotate one line or multiple lines

8. Select a statement

(only one is introduced)

 **if sentence**

 1) The first form is the basic form: if
      if(expression) sentence
   Its semantics is: if the value of the expression is true, the subsequent statement will be executed; otherwise, the statement will not be executed. The process can be represented as the following figure.

  1. Code demonstration:
#include<stdio.h>
int main()
{
    int a = 0;
    scanf("%d",a);
    if(a==1) //When a=1 is expressed in if, the = = sign is used to execute the statement. The = in the program is an assignment.
    {
        printf("study hard");
    }
    return 0;
}

The second form is: if else
If (expression)
Statement 1;
else
Statement 2;
Its semantics is: if the value of the expression is true, execute statement 1; otherwise, execute statement 2. The execution process can be represented as the following figure.

Code demonstration:

#include<stdio.h>
int main()
{
    int a = 0;
    scanf("%d",a);
    if(a==1) //When a=1 is expressed in if, the = = sign is used to execute the statement. The = in the program is an assignment.
    {
        printf("study hard");
    }
    else         //else when the input a is not 1, execute the following statement
    {
        printf("Don't study hard");
    }
    return 0;
}
  1. The third form is the if else if form
    The first two forms of if statements are generally used in the case of two branches. If else if statement can be used when multiple branches are selected. Its general form is:
    If (expression 1)
    Statement 1;
    Else if (expression 2)
    Statement 2;
    Else if (expression 3)
    Statement 3;
    ...
    Else if (expression m)
    Statement m;
    else
    Statement n;
    Its semantics is to judge the value of the expression in turn. When a value is true, the corresponding statement will be executed. Then jump outside the entire if statement and continue executing the program. If all expressions are false, the statement n is executed. Then proceed with the follow-up procedure. The execution process of if else if statement is shown in the following figure.

    Code demonstration:

    #include<stdio.h>
    int main()
    {
        int a = 0;
        scanf("%d",a);
        if(a==1) //When a=1 is expressed in if, the = = sign is used to execute the statement. The = in the program is an assignment.
        {
            printf("study hard");
        }
        else if(a==2)   //When a==2, execute the following statements of else if
        {
            printf("play a game");
        }
        else if(a==3)  //When a==3, execute the following statements of else if
        {
            printf("play a ball");
        }
        else         //else when input a is not 1, 2 or 3, execute the following statement
        {
            printf("Play other games");
        }
        return 0;
    }
    

    9. Circular statement

    The general form of the while statement is:
    While (expression) statement
    The expression is a loop condition and the statement is a loop body.

The semantics of the while statement is to calculate the value of the expression. When the value is true (not 0), the loop body statement is executed. The execution process can be shown in the figure below.

Code demonstration

#include<stdio.h>
int main()
{
    int time = 0;
     while(time<10000)  //Expression. If the expression is satisfied, the statement of the code block is executed
     {
         printf("study hard ");
         time ++;         	//Limiting the loop condition and not limiting the loop condition will become an endless loop, because time is always equal to 0,
     }                      //Add one for each time. After 10000 times, time=10000, and the cycle ends
    return 0;
}

10. Function

In C language, a function consists of a function header and a function body. All components of a function are listed below:

  • **Return type: * * a function can return a value. return_type is the data type of the value returned by the function. Some functions perform the required operation without returning a value. In this case, return_type is the keyword void.
  • **Function name: * * this is the actual name of the function. The function name and the parameter list together form the function signature.
  • **Parameters: * * parameters are like placeholders. When the function is called, you pass a value to the parameter, which is called the actual parameter. The parameter list includes the type, order and quantity of function parameters. Parameters are optional, that is, functions may not contain parameters.
  • **Function body: * * the function body contains a set of statements that define the function execution task.

A simple understanding of functions is used to enable the code to have its own functions, and to realize the independence of functionality

For example: find the larger value of two numbers. If we have this function, we can call it directly without writing it again.

#include<stdio.h>
int max(int num1, int num2)   //The returned data type is int, so it is received with int type
{                             //The two data received are int, so they are received with two int types
   /* Local variable declaration */
   int result = 0;
 
   if (num1 > num2)
      result = num1;
   else
      result = num2;
 
   return result;        
}
int main()
{
    int a = 0;
    int b = 0;
    scanf("%d%d",&a,&b);
    int ret = max(a,b);	//Function call format function name (); Here pass the values of a and b.
    printf("%d",ret);
}

The results are obvious, as shown in the figure

11. Array

How to store 1-10 numbers?

C language gives the definition of array: a set of elements of the same type

Definition of array
int arr[10]={1,2,3,4,5,6,7,8,9,10}; //Define int type array arr, [determine the size of the array], {place array elements};
Subscript of array

C language stipulates that each element of the array has a subscript, which starts from 0.

Arrays can be accessed by subscripts.

int arr[10]={1,2,3,4,5,6,7,8,9,10}; 
//The array has 10 elements with subscripts 0-9;

Use of arrays

Print array.

#include<stdio.h>
int main()
{
    int arr[10]={1,2,3,4,5,6,7,8,9,10}; 
    int i = 0;
    while(i<10)
    {
        printf("%d",arr[i]);   //Print 1-10;
        i++;
    }
    return 0;
}

Of course, you can also use a loop to enter values into the array

#include<stdio.h>
int main()
{
    int arr[10]={1,2,3,4,5,6,7,8,9,10}; 
    int i = 0;
    while(i<10)
    {
        scanf("%d",&arr[i]);   //Input 1-10;
        i++;
    }
    return 0;
}

12. Operator

Brief introduction

  • arithmetic operator

    * - + / %

    Arithmetic rules of Mathematics

  • Shift operators

    >> <<

    Shift the binary of a number

  • Bitwise operators

​ & ^ |

  • Assignment operator

    = += -= *= /= &= ^= |= >>= <<=

    Equivalent to n = n (arithmetic operator) m

  • unary operator

    Introduce the difference between pre + +, post + +
    Pre + +, pre -- add before use
    Post + +, post – use before add
    x

    #include<stdio.h>
    int main()
    {
        int a = 10;
        int b = ++a;
        int c = a++;
        printf("%d %d",b,c);
        return 0;
    }
    
  • Relational operator

    >

    >=

    <

    <=

    != Used to test "inequality"

    ==Used to test equality

  • Logical operator

    &&Logic and

    ||Logical or

    ternary operators

    exp1 ? exp2 : exp3

    comma expression

    exp1, exp2, exp3, ...expN

    Comma expressions are executed sequentially

    Subscript references, function calls, and structure members

    [] () . ->

13 common keywords

13.1typedef

typedef, as the name suggests, is a type definition, which should be understood here as type renaming.

#include<stdio.h>
typedef unsigned int uint_32;
int main()
{
	unsigned int num1 = 0;
	uint_32 num2 = 0;
	return 0;
}

The above code renames unsigned int to uint_32;

num1 and num2 have exactly the same data type

13.2 static

In C language:

static is used to modify variables and functions

  1. Decorated local variable - static local variable
  2. Decorated global variable - static global variable
  3. Modifier function - static function

1. Modify local variables

#include<stdio.h>
void test()
{
   int i = 0;
	i++;
	printf("%d ", i);
}
int main()
{
	int c = 0;
	while (c < 10)
	{
		test();
		c++;
	}
	return 0;
}

The result is obvious because every time you enter the test function

Variable i is assigned to 0, and after the function runs, variable i is destroyed (end of life cycle).

But after adding static to variable i

The following occurs

#include<stdio.h>
void test()
{
	static int i = 0;
	i++;
	printf("%d ", i);
}
int main()
{
	int C = 0;
	while (C < 10)
	{
		test();
		C++;
	}
	return 0;
}

Static changes variable i into static variable i, that is, the life cycle of variable i changes. Even if the function test runs, i will not be destroyed, and the value of i will not change and will not be re assigned, so as to achieve the effect of increasing

Conclusion:

Static modifies the local variable, which changes the life cycle of the variable, so that the static local variable still exists when it is out of the scope. The life cycle does not end until the end of the program.

2. Modify global variables

add.c(Another source file)
    int g_val = 2018;
test.c
#include<stdio.h>
extern int g_val; //statement
int main()
{
	printf("%d\n", g_val);
     return 0;
}

The result is no error

That is, in the same project, variables in different files have link properties. As long as they are declared, they can be used in other files

The results are shown in the figure

After static modification

add.c(Another source file)
    static int g_val = 2018;
test.c
#include<stdio.h>
extern int g_val; //statement
int main()
{
	printf("%d\n", g_val);
     return 0;
}

A connectivity error occurred

static modifies the global variable to make the external link attribute of the global variable become the internal link attribute, so that its scope is downgraded from the whole project to the whole file, that is, the scope becomes smaller, but the life cycle remains the same.

3. Modification function

add.c (Another source file)
   int add(int a ,int b)
{
    return a+b;
}
    
test.c
#include<stdio.h>
extern int g_val; //statement
int main()
{
    int a = 0;
    int b = 0;
    scanf("%d%d",&a,&b);
	int ret = add(a,b);
    printf("%d",ret);
     return 0;
}

It can run. The function also has the external link attribute. It can call functions in other files.

add.c (Another source file)
   static int add(int a ,int b)
{
    return a+b;
}
    
test.c
#include<stdio.h>
extern int g_val; //statement
int main()
{
    int a = 0;
    int b = 0;
    scanf("%d%d",&a,&b);
	int ret = add(a,b);
    printf("%d",ret);
     return 0;
}

The following error messages will appear when the code runs

That is, static modifies the function, so that this function can only be used in this source file, not in other source files. In fact, the function loses the external link attribute and becomes an internal link attribute

13.2 #define
#define MAX 100; // Define constants
#define add(x,y) ((x)+(y)) / / define macro
#include<stdio.h>
int main()
{
    int a = 5;
    int b = 6;
    int ret = add(a,b)
        //add(a,b) = ((a)+(b));
    return 0;
}

14 pointer

1 memory

Memory is a particularly important memory on the computer. The operation of programs in the computer is carried out in memory. Therefore, in order to use memory effectively, the memory is divided into small memory units, and the size of each memory unit is 1 byte. In order to effectively access each unit of memory, the memory unit is numbered. These numbers are called the address of the memory unit.

Look at the address of the following variables

#include<stdio.h>
int main()
{
    int a = 10;
    printf("%p",&a);
    //&Fetch address operator
    //%p is the print address
    return 0;
}

Variable a consists of four addresses

Only one address is printed, which is the first address of variable a.

Use pointer variable to operate the address of stored a

#include<stdio.h>
int main()
{
    int a = 10;
     int *p; //p is an integer pointer variable
     p=&a;  //Save a's address
    return 0;
}

Dereference operation variable a by pointer variable

#include<stdio.h>
int main()
{
    int a = 10;
     int *p; 
     p=&a;  
    *P = 20;
    return 0;
}

*Dereference operator

At this time, * p refers to A. use dereference and pointer to operate the value of variable a

Size of pointer variable

#include<stdio.h>
int main()
{
     printf("%d\n", sizeof(char *));
     printf("%d\n", sizeof(int *));
     printf("%d\n", sizeof(long *));
     printf("%d\n", sizeof(double *));
    return 0;
}

The results show that the size of the pointer variable is independent of the data type, and the size is 4 bytes

be careful:

The pointer size is 4 bytes on 32-bit platform and 8 bytes on 64 bit platform.

15. Structure

Structure is a particularly important knowledge point in C language. Structure makes C language capable of describing complex types.

For example, describing a person includes: Name + age + gender.

Only structure can be used here.

Initialization of structure

struct Stu
{    char name[20];//name
 int age;      //Age
 char sex[5];  //Gender
};

Use of structure

struct Stu
{    char name[20];//name
 int age;      //Age
 char sex[5];  //Gender
};
#include<stdio.h>
int main()
{
    //Structure information
        struct Stu s = {"Zhang San", 20, "male"};
    //. access operators for structure members
    printf("name = %s age = %d sex = %s\n", s.name, s.age, s.sex,);
    //->Operator's use of pointer variable structures
    struct Stu *ps = &s;  
    printf("name = %s age = %d sex = %s\n", ps->name, ps->age, ps->sex");
    return 0;
}

16 summary

After learning the basic grammar knowledge of c language, but this is only the tip of the iceberg. c language is the ancestor of almost all high-level languages on the market, and its complexity can be imagined. I hope to make persistent efforts in the future and continue to learn c language in depth. Encourage with you!

Posted by dkjohnson on Fri, 29 Oct 2021 19:57:49 -0700