C language learning [1]-understand the basic grammar

C language is a general-purpose, process-oriented computer programming language.

1. C program structure

C Hello World example

The C program mainly includes the following parts:

  1. Preprocessor directive
  2. function
  3. variable
  4. Statement & expression
  5. Annotation

Examples:

// 是预处理器指令,告诉 C 编译器在实际编译之前要包含 stdio.h 文件
#include <stdio.h>
// 是主函数,程序从这里开始执行
int main()
{
    
    
   /* 我的第一个 C 程序,注释内容 */
   ///*...*/ 将会被编译器忽略
   printf("Hello, World! \n");
   //结束程序,并返回0
   return 0;
}

2. C basic grammar

2.1 C's token

The C program is composed of various tokens, which can be keywords, identifiers, constants, string values, or a symbol.

2.2 Semicolon

In C programs, the semicolon is the end of a statement. In other words, each statement must end with a semicolon. It indicates the end of a logical entity.

2.3 Notes

C language has two comment methods:
// Single-line comment
/* */ Comments in this format can be single-line or multiple-line.
Note: You cannot nest comments within comments, and comments cannot appear in strings or character values.

2.4 Identifier

The C identifier is the name used to identify variables, functions, or any other user-defined items. An identifier starts with the letters AZ or az or underscore _, followed by zero or more letters, underscores, and numbers (0-9).
Note: C is a case-sensitive programming language

2.5 Keywords

That is reserved words. These reserved words cannot be used as constant names, variable names, or other identifier names.

2.6 C space

Lines that only contain spaces are called blank lines and may contain comments, and the C compiler will ignore them completely.
In C, spaces are used to describe whitespace, tabs, newlines, and comments. Spaces separate the parts of the statement, allowing the compiler to recognize where an element (such as int) in the statement ends and where the next element begins.

fruit = apples + oranges;   // 获取水果的总数

The space character between fruit and =, or = and apples is not necessary, but in order to enhance readability, you can add some spaces as needed.

3. C data type

In the C language, data types refer to a wide range of systems used to declare variables or functions of different types. The type of variable determines the space occupied by the variable storage and how to interpret the stored bit pattern.

3.1 Types in C can be divided into the following 4 categories

  1. Basic types: arithmetic types, including integer and floating-point types
  2. Enumeration type: is an arithmetic type, used to define that only certain discrete values ​​and variables can be assigned in the program
  3. Void type: The type specifier void indicates that there is no value available
  4. Derived types: pointer type, array type, structure type, union type, function type

Array types and structure types are collectively referred to as aggregate types.
The type of a function refers to the type of the return value of the function.

3.2 Details of the storage size and value range of standard integer types
Insert picture description here

Note: The size of various types of storage is related to the number of bits in the system, but currently 64-bit systems are the main ones.
In order to get the exact size of a certain type or a certain variable on a specific platform, you can use the sizeof operator. The expression sizeof(type) gets the storage byte size of the object or type.
printf("int storage size: %lu \n", sizeof(int));

3.3 Details of the storage size, value range and precision of the standard floating-point type The
Insert picture description here
example will output the storage space occupied by the floating-point type and its range value:

#include <stdio.h>
#include <float.h>
//头文件 float.h 定义了宏,在程序中可以使用这些值和其他有关实数二进制表示的细节
int main()
{
    
    
   printf("float 存储最大字节数 : %lu \n", sizeof(float));
   printf("float 最小值: %E\n", FLT_MIN );
   printf("float 最大值: %E\n", FLT_MAX );
   printf("精度值: %d\n", FLT_DIG );
   
   return 0;
}
//%E 为以指数形式输出单、双精度实数
//在 Linux 上编译并执行上面的程序时,它会产生下列结果
float 存储最大字节数 : 4 
float 最小值: 1.175494E-38
float 最大值: 3.402823E+38
精度值: 6

3.4 void type
void type specifies no value available
Insert picture description here

4. Variables

  • A variable is really just the name of a memory area that the program can manipulate. Each variable in C has a specific type. The type determines the size and layout of the variable storage. Values ​​in this range can be stored in memory, and operators can be applied to variables.
  • The name of a variable can consist of letters, numbers, and underscore characters. It must start with a letter or underscore. Uppercase and lowercase letters are different because C is case sensitive.

Basic types:
Insert picture description here
C language also allows the definition of various other types of variables, such as enumerations, pointers, arrays, structures, unions, etc.

4.1 Definition of variables

Variable definition is to tell the compiler where to create the storage of the variable, and how to create the storage of the variable. The variable definition specifies a data type and contains a list of one or more variables of that type.
type variable_list;

type must be a valid C data type, which can be char, w_char, int, float, double or any user-defined object. variable_list can consist of one or more identifier names, and multiple identifiers are separated by commas .

example:

int    i, j, k;
char   c, ch;
float  f, salary;
double d;

Variables can be initialized at the time of declaration (specify an initial value). The initializer consists of an equal sign followed by a constant expression:
type variable_name = value;

example:

extern int d = 3, f = 5;    // d 和 f 的声明与初始化
int d = 3, f = 5;           // 定义并初始化 d 和 f
byte z = 22;                // 定义并初始化 z
char x = 'x';               // 变量 x 的值为 'x'

Definition without initialization: Variables with static storage duration will be implicitly initialized to NULL (the value of all bytes are 0), and the initial values ​​of all other variables are undefined.

4.2 Declaration of variables

The variable declaration assures the compiler that the variable exists with the specified type and name, so that the compiler can continue further compilation without knowing the complete details of the variable.

The variable declaration only has its meaning at compile time, and the compiler needs the actual variable declaration when the program is linked.

There are two cases of variable declaration:

1. One is the need to establish storage space. For example: int a has already established storage space when it is declared.

2. The other one does not need to establish storage space, by using the extern keyword to declare the variable name without defining it.

For example: extern int a The variable a can be defined in other files.

3. Unless there is an extern keyword, it is the definition of a variable.

extern int i; //声明,不是定义
int i; //声明,也是定义

If you need to reference a variable defined in another source file in one source file, we only need to add the extern keyword declaration to the variable in the referenced file.

#include <stdio.h>
/*外部变量声明*/
extern int x ;
extern int y ;
int addtwonum()
{
    
    
    return x+y;
}

Quoting it:

#include <stdio.h>
  
/*定义两个全局变量*/
int x=1;
int y=2;
int addtwonum();
int main(void)
{
    
    
    int result;
    result = addtwonum();
    printf("result 为: %d\n",result);
    return 0;
}

4.3 Lvalues ​​and Rvalues ​​in C

There are two types of expressions in C:

1. Lvalue (lvalue): An expression that points to a memory location is called an lvalue expression. The left value can appear on the left or right of the assignment number.

2. Rvalue: The term rvalue refers to the value stored at some address in memory . An rvalue is an expression that cannot be assigned, that is, an rvalue can appear on the right side of the assignment number, but cannot appear on the left side of the assignment number.

The variable is an lvalue, so it can appear to the left of the assignment number. Numeric literals are rvalues, so they cannot be assigned and cannot appear on the left side of the assignment number.

5. Constant

Constants are fixed values ​​and will not change during program execution. These fixed values ​​are also called literals.

Constants can be any basic data type, such as integer constants, floating-point constants, character constants, or string literals, as well as enumeration constants.

Constants are like regular variables, except that the value of a constant cannot be modified after it is defined.

5.1 Integer constant

Integer constants can be decimal, octal, or hexadecimal constants. The prefix specifies the radix: 0x or 0X means hexadecimal, 0 means octal, and without a prefix, it means decimal by default.

An integer constant can also have a suffix. The suffix is ​​a combination of U and L. U represents an unsigned integer (unsigned), and L represents a long integer (long). The suffix can be uppercase or lowercase, and the order of U and L is arbitrary.

5.2 Floating-point constants

Floating-point constants consist of an integer part, a decimal point, a decimal part, and an exponent part. You can use decimal form or exponential form to represent floating-point constants.

When expressed in decimal form, it must include an integer part, a decimal part, or both.

When expressed in exponential form, the decimal point, exponent, or both must be included. Signed exponents are introduced with e or E.

3.14159       /* 合法的 */
314159E-5L    /* 合法的 */
510E          /* 非法的:不完整的指数 */
210f          /* 非法的:没有小数或指数 */
.e55          /* 非法的:缺少整数或分数 */

5.3 Character constants

Character constants are enclosed in single quotes. For example,'x' can be stored in a simple variable of type char.

The character constant can be an ordinary character (such as'x') , an escape sequence (such as'\t'), or a general character (such as'\u02C0').

In C, there are some specific characters. When they are preceded by a backslash, they have a special meaning, and they are used to represent such as newline (\n) or tab (\t).

Insert picture description here

5.4 String constants

String literals or constants are enclosed in double quotes "". A string contains characters similar to character constants: ordinary characters, escape sequences, and general characters.

You can use spaces as delimiters to break a long string constant into lines.

5.5 Define constants

In C, there are two simple ways to define constants:
1. Use #define preprocessor

#define identifier value

2. Use the const keyword

You can use the const prefix to declare constants of the specified type

const type variable = value;

Note: It is a good programming practice to define constants as capital letters.

Guess you like

Origin blog.csdn.net/qq_46009608/article/details/110200517