【C语言进阶】宏定义与条件编译的7种高阶应用:静态断言、标识符转字符串、连接运算符、代码加密(附完整示例)

📅 发布时间:2026/7/6 5:27:27 👁️ 浏览次数:
【C语言进阶】宏定义与条件编译的7种高阶应用:静态断言、标识符转字符串、连接运算符、代码加密(附完整示例)
1、宏定义与条件编译实现静态断言的代码错误自动检测#define_CRT_SECURE_NO_WARNINGS#includestdio.h#includeWindows.h//#define NDEBUG#ifndefNDEBUG#definemyassert(x)\if(!(x)){\charstr[100]{0};\sprintf(str,当前函数名为%s文件名为%s代码行号为%d\n,__FUNCTION__,__FILE__,__LINE__);\printf(myassert(%s)条件不满足\n,#x);\printf(str); \MessageBoxA(0,str,小伙你的程序出错了,0);\}#else#definemyassert(x)#endifintmain(){intnum200;myassert(num100);printf(%d\n,num);return0;}2、单独的宏名才会被替换#includestdio.h#definePI 100intmain(){intPIPI20;printf(PI%d,PIPI%d,PI,PIPI);return0;}3、宏定义嵌套#includestdio.h#defineM 10#defineN 20#defineP MN#defineQ 100M-N#defineR Q-PM*N#defineOUT printf(%d,%d,%d,%d,%d\n,M,N,P,Q,R);intmain(){OUTreturn0;}4、终止宏定义、限制宏定义域作用范围#includestdio.h#defineM 10voidout(){printf(%d\n,M);}#undefMintmain(){out();//printf(%d\n,M);return0;5、用带参数的宏定义计算三角形的面积f(x)#includestdio.h#definef(x,y) (x)*(y)/2intmain(){printf(%d\n,f(5,6));return0;}6、类似函数的带参数的宏定义实现变量值的交换#includestdio.h#define change(x,y) {intt;tx;xy;yt;}intmain(){inta10,b20;printf(a%d,b%d\n,a,b);change(a,b);printf(a%d,b%d\n,a,b);return0;}7、使用带参数的宏定义求一个数的绝对值#includestdio.h#definef(x) (x)0?(x):(-1*x)intmain(){printf(%d,%d\n,f(10),f(-5));return0;}8、带参数的宏定义中括号的作用#includestdio.h#define f(x) x*x#definek(x) (x)*(x)intmain(){printf(%d,%d\n,f(28),k(28));return0;}9、用带参数的宏定义取两个数中的最小值#includestdio.h#definef(x,y) xy?y:x#definef2(x,y) (x)(y)?(y):(x)intmain(){printf(%d,%d\n,f(7,8),f(13,29));printf(%d,%d\n,f2(7,8),f2(13,29));return0;}10、用带参数的宏定义将变量名和函数名转化为字符串#includestdio.h#definef(x) #xintmain(){inta110;printf(%s%d,functin%s\n,f(a1),a1,f(main));return0;}11、用带参数的宏定义和##双井号运算符连接/粘合两个标识符#includestdio.h#define f(x) print##xvoidprint1(){printf(111\n);}voidprint2(){printf(222\n);}void print3(){printf(333\n);}intmain(){f(1)();f(2)();f(3)();return0;}12、宏定义实现语言翻译#include stdio.h#define 整数 int#define 程序开始 main#define 打印 printf#define 返回 return#define 输出语句 China is great\n整数 程序开始(){打印(输出语句);返回 0;}13、宏定义实现代码加密#include stdio.h#define _ int#define __ main#define ___ printf#define ____ return#define _____ China is great\n#define ______ (#define _______ )#define ________ {#define _________ }#define __________ 0#define ___________ ;_ __ ______ _______ ___________ ______ _____ _______ _______________ __________ ____________________计算机科学与技术 计算机网络技术双专业课程体系完全导航指南