c–> #define 定义宏(C — > #define define macro)

#define 定义宏

宏(Macro)是预处理命令的一种,它允许用一个标识符来表示一个字符串

1.有关定义宏的代码末尾不需要添加”;”(分号)

2.定义宏define在计算的式子中相当于替代,类似于数学中的需要带入数值的x

#include <stdio.h>
#define ADD(x,y) x+y
int main(){
	printf("%d\n", 3 * 2 + ADD(2, 2) * 2);//3*2+2+2*2=12
	return 0;
}
#include <stdio.h>
#define ADD(x,y) (x+y)
int main(){
	printf("%d\n", ADD(2, 2) * 3);//(2+2)*3=12
	return 0;
}

3.宏定义必须写在函数之外,其作用域为宏定义命令起到源程序结束。如要终止其作用域可使用命令。例如:

#undef
#define PI 3.14159

int main(){
    // Code
    return 0;
}

#undef PI

void func(){
    // Code
}

表示 PI 只在 main() 函数中有效,在 func() 中无效。

4.代码中的宏名如果被引号包围,那么预处理程序不对其作宏代替,例如:

#include <stdio.h>
#define OK 100
int main(){
    printf("OK\n");
    return 0;
}

运行结果:OK

语法:

define 宏名 宏的内容

带参宏定义的一般形式为:

#define 宏名(形参列表) 字符串

有两种形式:

类似与定义常量:

 #define MAX 100

类似与定义函数:

#define ADD(x,y) x+y
————————

#define 定义宏

Macro is a kind of preprocessing command, which allows an identifier to represent a string

1. There is no need to add “;” at the end of the code for defining macros (semicolon)

2. Defining the macro define is equivalent to substitution in the calculation formula, which is similar to the X that needs to be brought into the value in mathematics

#include <stdio.h>
#define ADD(x,y) x+y
int main(){
	printf("%d\n", 3 * 2 + ADD(2, 2) * 2);//3*2+2+2*2=12
	return 0;
}
#include <stdio.h>
#define ADD(x,y) (x+y)
int main(){
	printf("%d\n", ADD(2, 2) * 3);//(2+2)*3=12
	return 0;
}

3. The macro definition must be written outside the function, and its scope is from the macro definition command to the end of the source program. To terminate its scope, use the command. For example:

#undef
#define PI 3.14159

int main(){
    // Code
    return 0;
}

#undef PI

void func(){
    // Code
}

Indicates that Pi is only valid in the main() function, not in func().

4. If the macro name in the code is surrounded by quotation marks, the preprocessor will not replace it with a macro, for example:

#include <stdio.h>
#define OK 100
int main(){
    printf("OK\n");
    return 0;
}

Operation result: OK

Syntax:

Define macro name macro content

The general form of macro definition with parameters is:

#Define macro name (parameter list) string

There are two forms:

Similar to defining constants:

 #define MAX 100

Similar to defining functions:

#define ADD(x,y) x+y