[C language final chapter] Program environment and preprocessing

1. Diagram of the translation environment and execution environment of the program

insert image description here

2. Detailed preprocessing

1. Predefined symbols

__FILE__ //进行编译的源文件
__LINE__ //文件当前的行号
__DATE__ //文件被编译的日期
__TIME__ //文件被编译的时间
__STDC__ //如果编译器遵循ANSI C,其值为1,否则未定义

2.#define

1. #define definition identifier

#define MAX 1000
#define reg register //为 register这个关键字,创建一个简短的名字
#define do_forever for(;;) //用更形象的符号来替换一种实现
#define CASE break;case 在写case语句的时候自动把 break写上

2. #define define macro

#include <stdio.h>
#define mul(x) x*x
int main()
{
    
    
	int x = 5;
	printf("%d", mul(x +1));
	return 0;
}
  • The result is not 36, but 11, because the expression will be replaced directly, instead of calculating x+1 and then passing it to the macro body

3. # and ##

#define PRINT(a) printf("the value of " #a " is %d\n",a)
int main()
{
    
    
	int a = 10;
	int b = 20;
	int c = 30;
	PRINT(a);
	PRINT(b);
	PRINT(c);
	return 0;
}
  • #The role is to turn a macro parameter into a corresponding string
#define ADD(num,value) \
        sum##num += value
int main()
{
    
    
    int sum5 = 0;
    ADD(5,10);
    printf("%d", sum5);
    return 0;
}

The role of ## is to combine the symbols on both sides into one symbol

4. Comparison of macros and functions

Advantages of macros :

  1. Compared with functions, macros have fewer steps than functions in the maintenance of function stack frames, function parameter passing, function return value return, function stack frame destruction, etc., so it is faster than functions in terms of operating efficiency
  2. The parameters of a function must be of a specific type, while macros are type-agnostic
    Disadvantages of macros :
  3. Unless the macro is relatively short, the length of the code will be increased when replacing it, especially when the macro is used multiple times, it will affect the code execution efficiency
  4. Macro cannot be debugged
  5. Macro has no type, not strict enough
  6. Macros can cause operator precedence issues

3.undef

  • remove macro definition

Prevent header files from being double-included

#ifndefine
#define
header file content
#enif
or
#pragma once

Guess you like

Origin blog.csdn.net/wan__xia/article/details/129987496
Recommended