当前位置:网站首页>Deep anatomy of C language -- C language keywords

Deep anatomy of C language -- C language keywords

2022-07-06 08:39:00 Finally - null

Make a little progress every day , Persistence makes a big difference !!!

Preface :

  stay C Many keywords will be encountered in the process of language learning , Whether we really know the usage methods and usage scenarios of these keywords in detail , Now let's explain in detail C In language 32 Key words

1.C Overview of language keywords :

keyword                                         explain
auto                                            Declare automatic variables
short                                            Declare short integer variables or functions
int                                                Declare an integer variable or function
long                                            Declare long integer variables or functions
float                                            Declare floating-point variables or functions
double                                        Declare a double precision variable or function
char                                            Declare character type variables or functions
struct                                          Declare a structural variable or function
union                                          Declare shared data type
enum                                          Declare enumeration type
typedef                                      Used to alias data types
const                                          Declare read-only variable
unsigned                                    Declare an unsigned type variable or function
signed                                        Declare a symbolic type variable or function
extern                                        Declare variables are being declared in other files
register                                      Declare register variables
static                                          Declare static variables
volatile                                        Explain that variables can be implicitly changed during program execution
void                                            Declares that the function returns no value or takes no arguments , Declare no type pointer
if                                                Conditional statements
else                                            Conditional statement negates Branch ( And if Continuous use )
switch                                        For switch statements
case                                          Switch statement Branch
for                                              A circular statement
do                                              The body of a loop statement
while                                          The loop condition of a loop statement
goto                                          Jump statements without conditions
continue                                    End the current cycle , Start next cycle
break                                        Jump out of current loop
default                                      In the switch statement “ other ” Branch
sizeof                                        Calculate the data type length
return                                        Subroutine return statement ( With parameters , Or without parameters ) The loop condition

1. auto:

Is used to modify local variables

notes : Global variables cannot be modified

2.register:

The computer calculates data by CPU Calculated , When calculating CPU Will access data .

Where data is stored :

CPU Characteristics of accessing data :

Visit from top to bottom , The access speed is getting slower and slower

Defining variables :

Is to open up a space in memory for storage , When we need to use a variable with high frequency , Can pass register To modify .

register The characteristics of modification :

Put variables in memory into registers , To improve access efficiency :

notes :register Decorated variables cannot be used &, because & It is relative to the concept in memory

3.extern and static 

1. Recognize multiple files

explain :

//.h: We call it a header file , Generally contains function declarations , Variable declarations , Macro definition , Header file, etc (header)
//.c: We call it the source file , It generally includes function implementation , Variable definition, etc (.c:c Language ) 

test.h

test.c,main.c

Use function declaration , The header file contains , Macro definition, etc , Just include the header file include"test.h" 

2. Use of global variables and functions between multiple files  

1. Use of cross file functions :

main.c

#include"test.h"
int main()
{

	show();

	return 0;
}

test.c

#include"test.h"

void show()
{
	printf("haha\n");
}

summary : Cross file functions can be used directly without declaration ( There are warnings !).

reason : Function has an external link property

2. Use of cross file global variables :

test.c

int g_val = 100;

main.c

	printf("%d\n", g_val);

summary : Cross file global variables cannot be used directly , It needs to be declared :

Declare keywords :extern

Be careful :

extern int g_val = 100;   //err

  The statement does not open up space , Initialization and assignment are not possible

summary : When all variables are declared , Cannot set initial value !!!

3. Potential problems :

When a variable and function need to be used in multiple files , If you include , It will make the later maintenance cost higher and higher !

terms of settlement : Use .h file , The purpose is to organize the project structure , Reduce maintenance costs for large projects !

Other source files such as main.c Just include

#include"test.h"

 4. Problem optimization :

Declare functions and global variables in the header file

test.h

#pragma once  // Prevent header files from repeatedly containing 
#include<stdio.h>
extern int g_val;
extern void show();

Be careful :

Variable declarations must be accompanied by extern.

It is recommended to bring... With the function declaration extern.

 3.static

Through the above summary, it is clear that functions and global variables can be used across files .

What is the way to prevent functions and global variables from being used across files ?

The next step is right satic The functions of this keyword are analyzed one by one :

1.static Modify global variable

 

summary :static When modifying global variables , Global variables can only be used in this file and cannot be used across files .

reason : Changed the scope of the global variable

2.static Modify function :

No direct access :

Indirect access to

 main.c

int main()
{

	show_helper();
	return 0;
}

test.h


extern void show_helper();

test.c

static void show(int num)
{
	printf("%d\n", num);
}
void show_helper()
{
	show(20);
}

summary :static When decorating functions , This function can only be accessed in this file , It cannot be used directly in external or other documents

  reason : Changed the scope of the function

In actual projects static The role of : Project maintenance , Provide security  

3.static Modify local variables :

no need static modification :

static void fun()
{
	int i = 0;
	i++;
	printf("%d ", i);

}
int main()
{

	int i = 0;
	for (i = 0; i < 10; i++)
	{
		fun();
	}

	return 0;
}

explain : Local variables are temporary , The function call opens up space and initializes , Function ends to free space

For local variables static modification :

static void fun()
{
	static int i = 0;
	i++;
	printf("%d ", i);

}
int main()
{

	int i = 0;
	for (i = 0; i < 10; i++)
	{
		fun();
	}

	return 0;
}

 

explain : When a local variable is used static When decorating , Local variables are changed from stack area to static area , The declaration period of local variables is extended , At the end of a function call , The storage space of local variables is not destroyed .

5. Desperate three questions :

Why global variables can be accessed across files ?

Why functions can be accessed across files ?

explain : Projects of a certain scale , It must be multi file , Between multiple files , Data interaction must be carried out later , If you cannot cross file , High interaction costs , therefore C The language defaults to cross file access

Why temporary variables are temporary , The life cycle of global variables is global ?

 C Program address space :

notes :C Program address space is not memory , But in the process address space of the operating system .

4.sizeof:

sizeof: Calculate the space occupied by variables and types in memory , Unit is byte .

notes : Use %zu Print ,sizeof The return value of unsigned int( Unsigned shaping ).

1. Basic data type :

Built in type :

char    Character
short    Short
int        plastic
long    Long integer
long long    Long plastic surgery
float      Single precision floating point
double  Double precision floating point

#include<stdio.h>


int main()
{
	printf("%zu\n", sizeof(char));
	printf("%zu\n", sizeof(short));
	printf("%zu\n", sizeof(int));
	printf("%zu\n", sizeof(long));
	printf("%zu\n", sizeof(long long));
	printf("%zu\n", sizeof(double));
	printf("%zu\n", sizeof(float));


	return 0;
}

summary : Different types determine the space occupied by variables in the open space .

  Why do we need to open up space according to the type ?

explain : In essence, it is a reasonable division of memory , On demand .

C Why are there many types in languages ?

explain :  Because in real life, there are different calculation methods for different application scenarios , The required space is different . In essence, it is to solve the problem of diversified scenarios with the minimum cost .

  notes :sizeof Is an operator , It's not a function .

5.signed,unsigned And shaping the storage in memory :

1. Original code , Inverse code , Complement code

How data is stored in memory ?

Data is stored in memory in the form of binary complement .

Concept :

Original code : Write it directly in binary form .

Inverse code : The sign bits remain the same , The other bits are reversed bit by bit .

Complement code : Inverse code +1.

Sign bit : In binary , The highest bit represents the sign bit ,1 A negative number ,0 It means a positive number . 

2. Signed number : 

Storage :

Signed positive numbers :

Original code , Inverse code , The complement is the same

  Signed negative number :

Inverse code : The sign bits remain the same , The other bits are reversed bit by bit ;

Complement code : Inverse code +1 Get the complement .

Print :

Print in the form of original code :

Signed positive numbers :

Signed negative number :

Method 1:

  Method 2:

3. An unsigned number :

Do not distinguish between positive and negative numbers , Original code , Inverse code , The complement is the same

notes : For printing unsigned numbers %u

Positive unsigned number ;

  Negative unsigned number :

  explain : When variables are defined , Open up space , When -10 When it is converted into complement and stored in space , The type is an unsigned number , Therefore, the original inverse complement is the same . When outputting, the original code is the complement .

4. Conversion between decimal and binary :

formula :1 After that n individual 0, Namely 2 Of n Power

5. Large and small end : 

1. How to generate large and small ends :

When we choose to store the data of high weight bits or low weight bits to high address or low address, different choices will cause the problem of size end .

2. How to define the size end ?

Big end : Put the high byte order ( High weight bit ) The data of is stored in the low address , Put the low byte order ( Low weight bit ) The data of is stored in the high address .

The small end : Put the high byte order ( High weight bit ) The data of is stored in the low address , Put the low byte order ( Low weight bit ) The data of is stored in the high address .

3. How to test the size end ? 

6.if else sentence

Implementation rules :

1. Execute first () The expression in or function , Get true and false results

2. Conditions   Decision function

3. Conduct   Branch function

What is? bool type :

stay C99 Introduce... Into the standard _Bool type , Then it is written in the way of macro definition bool, The purpose is to achieve and C++ Medium bool Types should be compatible

#include<stdbool.h>// Pay attention to the header file 
int main()
{
	//x It means a bool Variable 
	bool x = true;

	return 0;
}

bool The space occupied by variables in memory :

bool The size of a variable occupying one byte in memory  

bool Application of type :

Floating point numbers and 0 Compare :

Precision loss of floating point numbers :

  Through the code display, it is found that floating-point numbers cannot pass == Compare , Therefore, floating-point variables and 0 Comparison cannot be used ==

So how to compare floating-point numbers ?

When floating-point numbers conform to a range by subtraction , Then the condition is true :

System range value :

Minimum value of double precision floating-point number :2.2204460492503131e-016

Minimum value of single precision floating-point number :1.192092896e-07F

Floating point numbers and 0 Value comparison :

Pointer variables and 0 Comparison of values :

if And else The matching principle of

else Matching adopts the principle of proximity  

7.switch case sentence

switch( Integer variables / Constant / Integer expression )

{
     case var1:
         break;
    case var2:
         break;
    case var3:
         break;
    default:
         break;
}

case: Decision function

break: Branch function

default: It is used to remind the user to report an error when the value entered by the user is incorrect , Can be placed in switch case Anywhere in the statement

notes : When case and break When defining variables in, you need to add {};

case: Integer constant :

8.do while for keyword :

//while
Conditional initialization
while( Conditions to determine ){
 // Business update
  Condition update
}
//for
for( Conditional initialization ; Conditions to determine ; Condition update ){
 // Business code
}
//do while
Conditional initialization
do{
     Condition update

}while( Conditions to determine );

notes :

whatever C The program will open three input and output streams by default when compiling :

stdin: The standard input   FILE* stdin    keyboard

stdout: standard output FILE*stdout  Monitor

stderr: The standard error FILE*stderr    Monitor

About getchar function : Character acquisition

Be careful 1:getchar Function reads characters into the input stream , When inputting, first input a character , And then press enter , Equivalent to entering two characters , Characters and ‘\n’, Therefore, the default line feed .

getchar The return value of the function :

Although we read characters , But the reason why the return value is integer is because :

If the read is successful : Return character ASCII value 【0,255】,

But the read failed : If the error message ASCCII Value exceeds 【0.255】 The scope of the , Unable to return the error message correctly , So set the return value to integer . 

When inputting or outputting through the keyboard , All of them are ” character “.

therefore :

9.break keyword :

10.continue keyword :

stay do while Circulation and while In circulation continue Jump to conditional judgment , stay for In circulation continue Jump to the place where the condition is better . 

11.goto keyword

Jump up :

Jump down :

12.void keyword  

1.void Can I define variables ?

Conclusion :void You can't define variables

reason :void Itself is interpreted by the compiler as an empty type , Mandatory not allowed to define variables

2.void Modify the return value of the function :

1. Act as a placeholder , Let the user know that there is no need to return a value .

2. Tell the compiler that this return value is unacceptable . 

void And a pointer :

void Can I define pointer variables ?

Conclusion : Pointer variables can be defined .

reason :void* Is a pointer variable , The pointer 32 The machine platform occupies 4 Bytes , stay 64 The machine platform occupies 8 Bytes .

void* Pointers can be accepted by any kind of pointer ,void* Accept any type of pointer . 

void* The pointer of cannot add or subtract :

void* Pointer of cannot dereference operation :

13.return keyword

#include<stdio.h>

char* show()
{
	char str[] = "hello bit";
	return str;
}
int main()
{
	char* s = show();
	printf("%s\n", s);
	return 0;
}

 1. Why do you output random values :

explain : When main Function call show Function to open a stack frame on the stack area ,str Create temporary local variables in show Function stack frame , When show After the function is called , Release space .

2. Function details :

When creating function stack frames , How to determine the size of the development space ?

answer : When compiling, the compiler determines the size of the opening space through the temporary variables created inside the function .

When the function is called , Whether to clear all data when releasing space ?

answer : When the function is called , Invalid function internal data , Not clearing all data , Pictured above ,show After the function is called ,str The data content still exists , It's not cleared , But the call printf Function , Create stack frame overlay show Stack frame of function .

return Returns a local variable :

The function frees up space after it is called , The data inside the function will also be invalid , Then why did it return a Value ?

Understand from the perspective of disassembly :

 

explain : When creating local variables , Save the value of the local variable in the register (eax) in , When it returns, it will be saved in the register eax Value (a) Assign to ret.

14.const keyword

1.const Modify general variables :

const When modifying variables, they have constant attributes , Can not be direct modify .

It can be modified by pointer :

notes :const Putting in front of a type is equivalent to putting after a type

 

since const Modified variables can be modified through pointers , that const What is the meaning of ?

answer :1. For the compiler to report errors in advance when compiling , Improve the quality of your code .

2. use const Remind programmers when decorating const Modified variables cannot be modified .

2.const Modify the array :

const When decorating arrays , Every element of the array cannot be modified . 

3.const Modify pointer variables :

1.const Put it in * Left side :

p The variable pointed to cannot be directly modified ,p The contents of can be modified . 

2.const Put it in * To the right of

 p The variable pointed to can be modified ,p The content of cannot be modified .

3.const Both on * The left side of is placed on the right

 p The variable pointed to cannot be modified ,p The content of cannot be modified .

4.const Modify function

1.const Modify the parameters of the function :

Function parameters cannot be modified . 

2.const Modify the return value of the function :

 const When decorating the return value of a function, it cannot be in the form of a pointer , Modify the value of the internal variable of the function

15. Variable keywords —volatile

volatile Keywords can be used to remind the compiler , The variables defined later may be modified at any time , therefore CPU When accessing data , Will read data directly from the address of the variable , without volatile Keyword modification , Then the compiler may optimize reading and storage , It is possible to temporarily use the value in the register , If this variable is updated by another program , There will be inconsistencies .

volatile int flag = 1;
int main()
{
	while (flag)
	{
		;
	}

	return 0;
}

9. Structure keywords ——struct

The meaning of structure type : To describe a complex object

Define a student type :

Why are there two ways to access structure ?

When we pass parameters in a function , The parameter is structure type , Memory can be saved when using pointer access .

16. Consortium keyword ——union

Members share a memory space : Space development takes the largest member as the standard to apply for space from memory

The spatial distribution of consortium members in memory :

summary : Any member of the consortium , The starting address is the same  

b Forever a At the low address of , Every element considers itself the first element when using this space .

example : Judge the big and small ends :

  Ideas :

17. Enumerate keywords ——enum

enum: Is a set of constants with strong correlation , Highlight relevance .

  Value if not initialized, the default is from 0 Start , Every time it's self increasing 1, If it is initialized, it will increase automatically from the initialization value 1.

advantage :

18. Type renaming ——typedef

1.typedef Rename various types

2.typedef And #define The difference between :

 #define Simply replace the text ,typedef Is to rename the type , It is equivalent to defining a new type

19. Summary of keyword types :

1. Data type key :


char : Declare character type variables or functions
short : Declare short integer variables or functions
int : Declare an integer variable or function
long : Declare long integer variables or functions
signed : Declare a symbolic type variable or function
unsigned : Declare an unsigned type variable or function
float : Declare floating-point variables or functions
double : Declare a double precision variable or function
struct : Declare a structural variable or function
union : Declare a common body ( union ) data type
enum : Declare enumeration type
void : Declares that the function returns no value or takes no arguments , Declare no type pointer

2. Control statement keywords :

1. Cycle control (5 individual )
                for : A circular statement
                do : The body of a loop statement
                while : The loop condition of a loop statement
                break : Jump out of current loop
                continue : End the current cycle , Start next cycle
2. Conditional statements (3 individual )
                if : Conditional statements
                else : Conditional statement negates Branch
                goto : Jump statements without conditions
3. Switch statement (3 individual )
                 switch : For switch statements
                case : Switch statement Branch
                default : In the switch statement “ other ” Branch

4. Return statement (1 individual )
                return : Function return statement ( With parameters , Also see without parameters )

3. Storage type key :

Storage type key (5 individual )
                        auto : Declare automatic variables , Generally not used
                        extern : Declared variables are declared in other files
                        register : Declare register variables
                        static : Declare static variables
                        typedef : Used to alias data types ( However, the keyword is classified into storage keyword categories , Although it doesn't seem relevant

notes : Storage type keywords cannot appear at the same time , That is to say, only one variable can be defined

4. Other keywords :

const : Declare read-only variable
sizeof : Calculate the data type length
volatile : Explain that variables can be implicitly changed during program execution

That's right C Detailed explanation of all keywords of the language , I hope I can learn C It helps you in the process of language .

原网站

版权声明
本文为[Finally - null]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207060828327437.html