当前位置:网站首页>preprocessor directives
preprocessor directives
2022-07-25 20:34:00 【Smart Knight】
Catalog
Edit one 、 Predefined symbols #define
3、 ... and 、 Macros and functions
1. Macro parameters with side effects
2. Advantages and disadvantages of macros
3. The comparison between macro and function
Four 、 Conditional compilation
1. Conditional compilation instructions
2.#include "filename" And #include
One 、 Predefined symbols #define
1. Built-in symbol
These predefined symbols are built into the language .
__FILE__ | Source files to compile |
__LINE__ | The current line number of the file |
__DATE__ | The date the file was compiled |
__TIME__ | When the file was compiled |
__STDC__ | If the compiler follows ANSI C, Its value is 1, Otherwise, it is not defined |
Take a chestnut :
#include<stdio.h>
int main()
{
printf("file:%s line:%d\n", __FILE__, __LINE__);
return 0;
}
// result :file:D:\ Code \ Preprocessing instructions and macros \ Source .c line : 122.#define Define identifier
// The identifier and the macro we will talk about below only replace the text
#define MAX 1000
// Identifier constant
#define MAX 1000;
// When defining an identifier , Don't write in the back ; Syntax errors may occur
#define MAX 1000
#define condition MAX>0;
if (condition)
max = MAX;
else
max = 0;
// Here, because the replacement part contains ; It becomes the following code , Then the grammar is wrong
if (1000>0;)
max = 1000;
else
max = 0;
#define reg register
// by register This keyword , Create a short name
#define do_forever for(;;)
// Replace an implementation with a more vivid symbol
#define CASE break;case
// Writing case Automatically put break write .
#define DEBUG_PRINT printf("file:%s\tline:%d\t \
date:%s\ttime:%s\n" ,\
__FILE__,__LINE__ , \
__DATE__,__TIME__ )
// If you define stuff Too long , It can be divided into several lines
// Except for the last line , Add a backslash after each line ( Line continuation operator )
// This symbol is only used for line breaking , Will not be read as characters .3.#define Defining macro
#define The mechanism includes a provision , Allow parameters to be replaced with text , This implementation is often called a macro (macro) Or define macro (define macro).
Here's how the macro is declared :#define name( parament-list ) stuff
Among them parament-list It's a list of symbols separated by commas , They may appear in stuff in .
Be careful : The left parenthesis of the argument list must be the same as name Next door neighbor . If there is any gap between the two , The parameter list will be interpreted as stuff Part of .
#include<stdio.h>
#define MULTIPLE(X) X*X
// Macros pass parameters first 10, Then replace the original macro part with 10*10
// Macros do not calculate , The expression result is finally calculated by the program
int main()
{
int a = 10;
printf("%d", MULTIPLE(a));
return 0;
}
// result :100However, such a definition is problematic
#include<stdio.h>
#define MULTIPLE(X) X*X
int main()
{
printf("%d", MULTIPLE(5+1));
return 0;
}
// result :11We want to calculate 6 The square of , The result was wrong . This is because macros only replace ,MULTIPLE(5+1) Be replaced by 5+1*5+1, The result after calculation is of course equal to 11 了
So when we define macros , Brackets should be added to all parts and the whole , In short, don't be stingy with parentheses on macro definitions
#include<stdio.h>
#define MULTIPLE(X) ((X)*(X))
int main()
{
printf("%d", MULTIPLE(5 + 1));
return 0;
}
// result :36Two 、# And ##
1.#
#include<stdio.h>
#define VALUE(A) printf("the value of "#A" is %d\n",A)
int main()
{
//printf This function can print multiple strings
// Realize a macro print the value of Variable name is A variable's value
int a = 1;
VALUE(a);
int b = 2;
VALUE(b);
VALUE(b+1);
return 0;
}
//printf("the value of "#A" is %d\n", A)
//#A Express the A This variable name is converted to a string
//VALUE(a); After replacement :printf("the value of ""a"" is %d\n",a); Can also complete the task
// result :the value of a is 1
//the value of b is 2
//the value of b+1 is 32.##
#define ADD_TO_SUM(num, value) \
sum##num += value;
int main()
{
int sum5 = ADD_TO_SUM(5, 10);// Role is : to sum5 increase 10.
printf("%d", sum5);
return 0;
}
//ADD_TO_SUM(num, value) sum##num += value;
// there num and value Replace first , Turn into sum##5 += 10;
// then ## take sum and 5 combined , Turn into sum5 += 10;These two instruction symbols are basically not used , Just see and know
3、 ... and 、 Macros and functions
1. Macro parameters with side effects
#include<stdio.h>
#define MAX(a,b) ((a)>(b)?(a):(b))
int main()
{
int x = 5;
int y = 8;
int z = MAX(x, y);
printf("x=%d y=%d z=%d\n", x, y, z);
// Replace :int z = ((5)>(8)?(5):(8))
// result :x=5 y=8 z=8
z = MAX(x++, y++);
printf("x=%d y=%d z=%d\n", x, y, z);
// Replace :int z = ((5++)>(8++)?(5++):(8++))
// Step 1 compare sizes :5<8, The result is false , meanwhile 5 and 8 Add one ,((6)>(9)?(6++):(9++))
// After taking value 9++, First use assignment z by 9, Add one after the original data to 10
// result :x=6 y=10 z=9
return 0;
}2. Advantages and disadvantages of macros
The advantages of macro :
- The code used to call and return from the function may take more time than actually performing this small computation . So macros are better than functions in terms of program size and speed .
- More importantly, the parameters of a function must be declared as specific types . So functions can only be used on expressions of the right type . On the contrary, how can this macro be applied to shaping 、 Long integer 、 Floating point type can be used for > To compare the types of . Macros are type independent .
The disadvantages of macro :
- Every time you use a macro , A macro defined code will be inserted into the program . Unless the macro is short , Otherwise, the length of the program may be greatly increased .
- Macros can't be debugged .
- Macro is type independent , It's not rigorous enough .
- Macros can cause operator priority problems , It is easy for Cheng to make mistakes .
3. The comparison between macro and function
Belong to sex | #define Defining macro | function |
generation code Long degree | Every time I use it , Macro code is inserted into the program . Except for very small macros , The length of the program will increase significantly | Function code only appears in one place ; Every time you use this function , Call the same code in that place |
Of board That's ok speed degree | faster | There is an extra cost of calling and returning functions , So it's relatively slow |
fuck do operator optimal First level | Macro parameters are evaluated in the context of all surrounding expressions , Unless you put parentheses , Otherwise, the priority of adjacent operators may have unpredictable consequences , Therefore, it is recommended that macros be written with more parentheses . | Function parameters are evaluated only once when the function is called , Its result value is passed to the function . The evaluation of expressions is easier to predict . |
belt Yes vice do use Of ginseng Count | Parameters may be replaced at multiple locations in the macro body , Therefore, parameter evaluation with side effects may produce unpredictable results . | Function parameters are evaluated only once when passing parameters , The result is easier to control . |
ginseng Count class type | Macro parameters are type independent , As long as the operation on parameters is legal , It can be used for any parameter type . | The arguments to the function are type dependent , If the type of parameter is different , You need different functions , Even if they perform different tasks . |
transfer try | Macros are inconvenient to debug | Functions can be debugged statement by statement |
Deliver return | Macros cannot be recursive | Functions can be recursive |
Naming conventions | All letters of the macro are capitalized | Functions don't have all the letters in uppercase |
Four 、 Conditional compilation
1. Conditional compilation instructions
1. Basic condition compilation
#if Constant expression
//...
#endif// Constant expressions are evaluated by the preprocessor .
2. Conditional compilation of multiple branches
#if Constant expression
//...
#elif Constant expression
//...
#else
//...
#endif
3. Judge whether it is defined
#if defined(symbol)
#ifdef symbol
#if !defined(symbol)
#ifndef symbol
4. Nested instruction
#if defined(OS_UNIX)
#ifdef OPTION1
unix_version_option1();
#endif
#ifdef OPTION2
unix_version_option2();
#endif
#elif defined(OS_MSDOS)
#ifdef OPTION2
msdos_version_option2();
#endif
#endif2. give an example
#include<stdio.h>
#define DEBUG
#define A
#define B 1
int main()
{
#ifdef DEBUG
printf("hello world\n");
#endif // DEBUG
// If DEBUG It is defined and compiled
#undef A
// Remove defined A
#ifndef A
printf("haha\n");
#endif // !A
// If A Compile without being defined
#if B == 1
printf("hhhhh\n");
#elif B == 2
printf("wwwww\n");
#else
printf("rrrrr\n");
#endif
// Be similar to if、else sentence , When the expression is judged to be true, the internal content will be compiled
return 0;
}5、 ... and 、 File contains
1.#include
We already know , #include Instruction can cause another file to be compiled . It's like it actually appears in #include It's the same place as the command . It's a simple alternative : The preprocessor first removes this instruction , And replace... With the contents of the containing file . Such a source file is contained 10 Time , So it's actually compiled 10 Time
Add in front #pragma once The duplicate header file will be included only once
#ifndef A
define A
include<stdio.h>
#endif
// That's ok 2.#include "filename" And #include
Look up the header file and go directly to the standard path , If no compilation error is found .
#include "filename" The program will first look for the header file in the default folder of the program , Then go to C Look in the built-in Library of the language .
#include I'll go straight to C Look in the built-in Library of the language .
Actually , For library files, you can also use "" The form of includes . But this is less efficient , Of course, it is not easy to distinguish between library files and local files .
summary : Actually C The language also has many preprocessing instructions , Such as #error、#pragma、#line etc. , We can learn more about
C The language part ends
边栏推荐
- Increase swap space
- 2022.7.24-----leetcode.1184
- [today in history] July 18: Intel was founded; The first photo was posted on the world wide web; EBay spins off PayPal
- Advantages of network virtualization of various manufacturers
- Chinese son-in-law OTA Ono became the first Asian president of the University of Michigan, with an annual salary of more than 6.5 million!
- 【云原生 | 从零开始学Kubernetes】八、命名空间资源配额以及标签
- [today in history] July 5: the mother of Google was born; Two Turing Award pioneers born on the same day
- Leetcode customs clearance: hash table six, this is really a little simple
- Apache Mina framework "suggestions collection"
- 从底层结构开始学习FPGA(16)----PLL/MMCM IP的定制与测试
猜你喜欢

Advantages of network virtualization of various manufacturers

从底层结构开始学习FPGA(16)----PLL/MMCM IP的定制与测试
![[cloud native] use of Nacos taskmanager task management](/img/af/f1c5359e7dbcf51f02fa32839539b2.png)
[cloud native] use of Nacos taskmanager task management

Cloud native, Intel arch and cloud native secret computing three sig online sharing! See you today | issues 32-34

Kubernetes advanced part learning notes

Difference Between Accuracy and Precision

各厂商网络虚拟化的优势

【高等数学】【1】函数、极限、连续

参与开源社区还有证书拿?

Clickhouse notes 02 -- installation test clickvisual
随机推荐
FormatDateTime说解[通俗易懂]
QML combines qsqltablemodel to dynamically load data MVC "recommended collection"
[Infographics Show] 248 Public Domain Name
【单细胞高级绘图】07.KEGG富集结果展示
"Share" devaxpress asp Net v22.1 latest version system environment configuration requirements
The uniapp project starts with an error binding Node is not a valid Win32 Application ultimate solution
[paper reading] unpaired image to image translation using cycle consistent advantageous networks
CarSim simulation quick start (XV) - ADAS sensor objects of CarSim sensor simulation (1)
During the interview, I was asked how to remove the weight of MySQL, and who else wouldn't?
Automated testing ----- selenium (I)
[today in history] July 17: Softbank acquired arm; The first email interruption; Wikimedia International Conference
[Infographics Show] 248 Public Domain Name
Today's sleep quality record 75 points
“链”接无限可能:数字资产链,精彩马上来!
[advanced mathematics] [4] indefinite integral
"Chain" connects infinite possibilities: digital asset chain, wonderful coming soon!
Network RTK UAV test [easy to understand]
[leetcode] 28. Implement strstr ()
SecureCRT garbled code solution [easy to understand]
10.< tag-动态规划和子序列, 子数组>lt.53. 最大子数组和 + lt.392. 判断子序列 dbc
