当前位置:网站首页>Basic grammar of C language
Basic grammar of C language
2022-07-29 04:36:00 【Once_ day】
C Basic grammar of language
Author:onceday date:2022 year 7 month 19 Japan
1. Overview
C Language is 1972 By the United States in Dennis Ritchie Designed and invented , And for the first time in UNIX Operating system DEC PDP-11 On the computer . It is made up of early programming languages BCPL (Basic Combind Programming Language) Developed and evolved .
C Languages have multiple versions , The earliest unified version is ANSI( National Institute of standards ) standard . After a C99,C11,C17,… etc. .
One c Language source program can be composed of one or more source files , Each source file has one and only one main function , The main function . But there can only be one main function in all source files .
The name of the main function need not be main, Any suitable name is enough , as long as c Initialization function _init) Just match the name inside .
2. data type
2.1 Basic types
Integer type , Character , floating-point , Enumeration type .
Character 、 Integer size and value range
| data type | Data length (32 position GNU compiler ) | Data length (64 position GNU compiler ) |
|---|---|---|
| char | 8bit | 8bit |
| unsigned char | 8bit | 8bit |
| short | 16bit | 16bit |
| unsigned short | 16bit | 16bit |
| int | 32bit | 32bit |
| unsigned int | 32bit | 32bit |
| long | 32bit | 64bit |
| unsigned long | 32bit | 64bit |
| long long | 64bit | 64bit |
| unsigned long long | 64bit | 64bit |
| The pointer | 32bit | 64bit |
C The standard specifies the minimum bit length of various integer types , So there is :
char = unsigned char <= short = unsigned short <= int = unsigned int <=
long = unsigned long <= long long =unsigned long long
Floating point number size and value :
(xxxxxxxxxxxx Need evidence xxxxxxxxxxx)
| data type | length (32 position gnu compiler ) | Significant figures | Value range |
|---|---|---|---|
| float | 32bit | 6-7 | 3.4*10(-38)`? |
| double | 64bit | ||
| long double | 96bit |
2.2 Construction type
An array type , Type of structure , Type of community
2.3 Pointer types
2.4 Empty type
3. Variable
3.1 Variable name
Variable name by number 、 Letter 、 Underline composition , The first character must be a letter , Underline plays a role of segmentation , Not as the first or last character of the variable name .
3.2 Type conversion
Automatic type is from low to high , In the same situation , From signed to unsigned .
In the expression , The type will automatically convert to the highest type , Finally, the precision loss type is converted back .
3.3 format conversion
printf/scanf Class function .
| The conversion character | Argument type : Output form |
|---|---|
| d,i | int: Decimal number |
| o | int: An unsigned octal number |
| x,X | int: Unsigned hexadecimal number |
| u | int: An unsigned decimal number |
| c | int: Single character |
| s | char*: Print sequentially until you encounter ’\0’ Or the number of characters specified by precision . |
| f | double: Decimal decimal represents . Default is 6. |
| e,E | double: Exponentially . The precision defaults to 6 |
| g,G | double: If the index is less than -4 Or greater than or equal to the accuracy , Then use %e/%E Output , Otherwise, use %f Format output , At the end of the 0 And decimal point do not print . |
| p | void* type : The pointer |
| % | Print a percent sign |
| - | Specifies that the converted variables are output in the form of left alignment , Default right alignment . |
| Numbers (.) | Specify the minimum field width , Other positions will be filled . |
| . | Separate field width from precision |
| (.) Numbers | Representation precision , Specify the maximum number of characters to print for a string , Floating point number decimal digits , The minimum number of digits of an integer . |
| h ,l | short The type and long type |
| + | Add... Before a signed number "+" or “'-' Number |
| 0 | When the value is aligned to the right , use 0 Fill in extra character positions |
| Space | Only for converting signed values , When the value is non negative , Add a space to its starting position . |
4. Constant
Here are several common constant representations :
| data type | Express |
|---|---|
| int | 123 |
| unsigned int | 123u |
| long | 123L |
| unsigned long | 123UL |
| float | 123.0f |
| double | 123.0 |
| long double | 123.0L |
| char | ‘a’ |
| char* | “ab” |
4.1 Symbolic constant
#define Symbol Constant
const type Symbol = expression ;
For macro documentation, see :https://blog.csdn.net/Once_day/article/details/124635280
Enumeration constants , Not given an initial value , Will be incremented according to the previous value , The first if not assigned , The default is 0.
enum Number {
one = 1,three= 3}
| Escape character | explain |
|---|---|
\' | Single quotation marks |
\" | Double quotes |
\\ | The backslash |
\0 | Null character |
\000 | octal |
\a | Beep |
\b | Back space |
\f | Page identifier |
\n | A newline |
\r | A carriage return |
\t | Horizontal tabs |
\v | Vertical tabs |
\xhh | Hexadecimal symbol |
4.2 Variable parameter macro
There are two kinds of , See the specific reference blog :https://blog.csdn.net/Once_day/article/details/124635280c
#define debug(format,arg...) printf(format,args)
#define debug(format,...) printf(format,##__VA_ARGS__)
The latter is a specially optimized macro , The problem of zero parameter can be eliminated . But different compilers support different formats , Special attention required .
5. Operator
5.1 Arithmetic operator
+ - * / % ++ --
Integer division results are rounded
% Operations cannot act on floating-point objects
By the negative operational component , The direction of integer division interception 、 Overflow and underflow need to be determined according to the specific machine conditions .
5.2 Relational and logical operators
> < >= <= == !=
&& || !
- Logical operators are evaluated from left to right , Once you know the result is true or false , Stop counting immediately .
5.3 Bitwise operators
& | ~ ^ << >>
These operators can only act on integer components
<< and >> The value of the operational component must be positive
5.4 Assignment operator
= += -= *= /= %= &= |= ^= >>= <<=
5.5 Conditional operator
xx ? xx:xx;
5.6 The comma operator
xxx,xxx;
int x = (3,4); // x =4
Expressions separated by commas are evaluated from left to right , The result and type are the rightmost expressions .
5.7 Special operators
Type converter () [] -> . * &
5.8 Priority of various operators
| priority | Operator | associativity |
|---|---|---|
| 1 | () [] -> . | L-R |
| 2 | ! ~ ++ – +( One yuan ) -( One yuan ) * & (type) | R-L |
| 3 | * / % | L-R |
| 4 | + - | L-R |
| 5 | << >> | L-R |
| 6 | < <= > >= | L-R |
| 7 | == != | L-R |
| 8 | & | L-R |
| 9 | ^ | L-R |
| 10 | ||
| 11 | && | L-R |
| 12 | | | |
| 13 | ?: | R-L |
| 14 | = += -= *= /= %= &= ^= |= <<= >>= | R-L |
| 15 | , | L-R |
6. Basic statement
expression ;
The name of the function ( Parameters ......);
Built in statement ;
There are three kinds of control words :
conditional :if,switch
Loop execution :while,do while ,for
Turn to statement :break,goto,continue,return
Such as :
for(i=1;i<=100;i++){
....}
break Can jump out of the innermost switch Or loop statement .
continue The function of the statement is to skip the remaining statements in this cycle and forcibly execute the next cycle .
continue Statements can only be used in for、while、do-while In isocycle .
6.1 function
Return type Function name ( Parameters ....)
{
Description sequence and statement sequence
}
Functions do not allow nested definitions !
Formal parameter and actual parameter :
The parameters of a function can be divided into formal parameters and actual parameters .
Formal parameters appear in function definitions , It can be used throughout the function body , Invalid after leaving this function .
Arguments appear in the main function , After entering the tuned function , Argument variables can't be used either .
When a function call occurs , The main function transfers the value of the real parameter to the formal parameter of the called function, so as to realize the data transfer from the main function to the called function .
The formal and actual parameters of a function have the following characteristics :
Parameter variables allocate memory units only when called , At the end of the call , Immediately release the allocated memory unit . therefore , Formal parameters are valid only within functions . The formal parameter variable cannot be used after returning the main calling function after the function call ends .
Arguments can be constant 、 Variable 、 expression 、 Functions, etc , Whatever the type of argument is , When you make a function call , They all have to have certain values , In order to pass these values to the parameter . Therefore, an assignment should be used in advance , Input and so on so that the argument gets a definite value .
In terms of quantity, actual parameters and formal parameters , On type , The order should be strictly consistent , Otherwise, a type mismatch will occur ” Error of .
The data transfer that occurs in a function call is one-way . That is, only the value of an argument can be passed to a formal parameter , You cannot pass the value of a formal parameter back to an argument . Therefore, in the process of function call , The value of the parameter changes , The value in the argument does not change .
return Used to return values , Its value should be consistent with the type of return value in the function definition . If the two are different , Then the function definition shall prevail , Automatic type conversion .
return ;// Nothing back
Function call : Function name ( Table of actual parameters )
Recursively call : A function can call itself directly or indirectly, which is called recursive call . This function is called a recursive function .
6.2 Functions and variables
Global variables : The scope is from the definition to the end of the whole file , Use... Before definition , You need to declare .
local variable : The effect is limited to the inside of braces . In the local position, the priority is higher than the external variable .
Static variables : Scope is limited to this document , Stored in global storage .
Register variables :
1) With keywords register The declared variable is called “ Register variables ”. Register variables are placed in machine registers , This makes the program smaller , Faster execution .
2) Only automatic variables and function parameters can be defined as register variables .
3) Cannot access the address of register variable .
4) When the number of register variables in the program exceeds the machine limit , The compiler ignores it .
7. Array
One dimensional array :
// Type specifier Array name [ Constant expression ]
initialization :
int latitude[] = {
0, 1, 2, 3, 4};
Reference element :
latitude[2];
Get the first address :
latitude;
&latitude[0];
stay C In language , Two dimensional arrays are arranged in rows . That is, put one line in sequence after the second line .
int a[3][4];
Assignment initialization :
int array[5][3]={
{
80,75,92},{
61,65,71},{
59,63,70},{
85,87,90},{
76,77,85} };
int array[5][3]={
80,75,92,61,65,71,59,63,70,85,87,90,76,77,85};
int array[][3]={
80,75,92,61,65,71,59,63,70,85,87,90,76,77,85};
int array[5][3]={
{
80},{
61},{
59},{
85},{
76}}; // Only some elements are initialized
array[1][1] = 65;
7.1 Array length calculation macro
#define ARRAY_LENGTH(x) (sizeof(x) / sizeof(x[0]))
7.2 C99 Array initialization method
Array: [index] = value
int a[6] = {
[4] = 29, [2] = 15 };
The equivalent is int a[6] = { 0, 0, 15, 0, 29, 0 };
[first … last] = value.
int widths[] = {
[0 ... 9] = 1, [10 ... 99] = 2, [100] = 3 };
8. The pointer
Type specifier * Variable name ;
Fetch address operator & Can only be applied to objects in memory ( Variables and array elements ), It cannot be applied to expressions 、 Constants or register variables .
Pointer to array :
Type specifier (* Pointer name )[ The length of the array ] ;
Pointing to the array :
Type specifier * Pointer name [ The length of the array ];
A function pointer :
Type specifier (* Pointer variable name )( Argument description table );
The return value is a function of a pointer :
Type specifier * Function name ( Argument description table );
Function pointer array :
Type specifier (* Pointer variable name [ The length of the array ])( Argument description table );
pointer to const :
const int *a;
constant pointer :
int * const a;
9. structure 、 The type definition 、 union
General form of structure definition :
struct Structure name {
Member list
};
Structure pointer :
struct Structure name * Structure pointer variable name
The structure nested definition must First of all .
Type definer typedef Used for user-defined type specifiers .
typedef Original type name New type name
All members of the union refer to the same location in memory . Variables used to store objects of different types and sizes at different times .
Structure position segment declaration :
struct registerinfo_s {
unsigned int command:5;
unsigned int error_code:8;
unsigned int write_protect:1;
unsigned int ready:1;
};
int Whether the type bit segment members are signed or unsigned .
Whether the members in the bit segment are allocated from left to right or right to left in memory .
Many compilers limit the length of bit segment members to the length of an integer value , So one can run on 32 Bit segment declarations on machines with bit integers may be in 16 Cannot run on a machine with bit integers .
In the bit field 2 Members , When the first 1 The remaining bits of member cannot accommodate 2 When a member , The compiler may put the 2 Members are placed in the next word in memory , It may also be placed directly on the No 1 After members .
Cannot take address for bit segment member .
10. Other instructions
Pretreatment reference :https://blog.csdn.net/Once_day/article/details/124635280c
because linux gcc By default, only libc, Therefore, the library function will be introduced later .
thorough c Grammar will be summarized in the form of special topics .
边栏推荐
- Back propagation process of manual BP neural network
- Don't stick to it for 68 days. Baboons eat bananas
- Implementation of jump connection of RESNET (pytorch)
- Definition and implementation of stack and queue (detailed)
- Deep analysis of data storage in memory (Advanced C language)
- C language: enumerating knowledge points summary
- Niuke IOI weekly 27 popularity group
- Use of torch.optim optimizer in pytorch
- 使用容器部署Jenkins
- [C language] power table of 3 generated by PTA 7-53
猜你喜欢

Update learning materials daily

9. Delay queue

使用容器部署Jenkins

Can you really write restful API?

Record the Niua packaging deployment project

Basic operation of queue

Don't insist on 66 days. Weight generates random numbers

JVM (heap and stack) memory allocation

String, array, generalized table (detailed)

Not for 61 days. The shortest word code
随机推荐
Niuke IOI weekly 27 popularity group
Mongo shell interactive command window
LeetCode_ Stack topics
安装spinning up教程里与mujoco对应的gym,报错mjpro150
Log configuration logback
6.pytest生成allure报告
MySQL - 聚簇索引和辅助索引
[c language] PTA 7-49 have fun with numbers (partially correct)
WebRTC实现简单音视频通话功能
[C language] PTA 7-91 output leap year
恒星科通邀您“湘”约第24届中国高速公路信息化大会暨技术产品展示会
论pyscript使用感想(实现office预览)
New year's greetings from programmers
C language force buckle question 61 of the rotating list. Double ended queue and construction of circular linked list
MySQL - 深入解析MySQL索引数据结构
VScode配置makefile编译
Definition and implementation of stack and queue (detailed)
TypeError: Cannot read properties of undefined (reading ‘then‘)
Vscode one click compilation and debugging
oracle 更新和删除数据