首页 > 代码库 > C语言学习笔记--C语言中的宏定义
C语言学习笔记--C语言中的宏定义
1. C 语言中的宏定义
(1)#define 是预处理器处理的单元实体之一(因此,预处理器只是简单的进行替换,并不
(2)#define 定义的宏可以出现在程序的任意位置(包括函数体的内部)
(3)#define 定义之后的代码都可以使用这个宏
2. 定义宏常量
(1)#define 定义的宏常量可以直接使用
(2)#define 定义的宏常量本质为字面量
3. 宏定义表达式
(1)#define 表达式的使用类似函数调用
(2)#define 表达式可以比函数更强大
(3)#define 表达式比函数更容易出错
#include <stdio.h>#define _SUM_(a, b) (a) + (b)#define _MIN_(a, b) ((a) < (b) ? (a) : (b))#define _DIM_(a) sizeof(a)/sizeof(*a)int main(){ int a = 1; int b = 2; int c[4] = {0}; int s1 = _SUM_(a, b); //(a)+(b) int s2 = _SUM_(a, b) * _SUM_(a, b); //(a)+(b)*(a)+(b) int m = _MIN_(a++, b); //((a++)<(b)?(a++):(b)) int d = _DIM_(c); //sizeof(c)/sizeof(*c); printf("s1 = %d\n", s1); // 3 printf("s2 = %d\n", s2); // 5 printf("m = %d\n", m); // 2 printf("d = %d\n", d); // 4 return 0;}
4. 宏表达式与函数的对比
(1)宏表达式被预处理器处理,编译器不知道宏表达式的存在
(2)宏表达式用“实参”完全替代形参,不进行任何运算。
(3)宏表达式没有任何的“调用”开销
(4)宏表达式中不能出现递归定义。
内置宏
#include <stdio.h>#include <malloc.h>#define MALLOC(type, x) (type*)malloc(sizeof(type)*x)#define FREE(p) (free(p), p=NULL)#define LOG(s) printf("[%s] {%s:%d} %s \n", __DATE__, __FILE__,__LINE__, s)#define FOREACH(i, m) for(i=0; i<m; i++)#define BEGIN {#define END }int main(){ int x = 0; int* p = MALLOC(int, 5); //以 int 类型作为参数! LOG("Begin to run main code...");FOREACH(x, 5) BEGIN p[x] = x; END FOREACH(x, 5) BEGIN printf("%d\n", p[x]); END FREE(p); LOG("End"); return 0;}
C语言学习笔记--C语言中的宏定义
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。