- 测试1(测试简单的宏展开)
- 测试2(测试简单的宏替换)
- 来看两个花括号测试(花括号能隔离环境)
- 测试1
- 测试2
- 测试宏函数(visual studio vc 无法使用复合语句表达式 ({}))
- C语言复合语句表达式 ({}) (只适用于gnu)
- 语法规则
- 示例1(在复合表达式中定义函数,调用函数,判断语句,以最后一个语句的值作为返回)
- 比较复杂的宏语句,以后再更。。。
- 参考文章
ubuntu上
如:
test.c
#define KY_GET_CURRENT_TIME (time)
int main(){
KY_GET_CURRENT_TIME(NULL);
return 0;
}
预处理:
[root@ubuntu /arnold_test/20220509_compile_preprocessing_test]3# gcc -E test.c # 1 "test.c" # 1 "" # 1 " " # 1 "/usr/include/stdc-predef.h" 1 3 4 # 1 " " 2 # 1 "test.c" int main(){ (time)(NULL); return 0; }
或:
[root@ubuntu /arnold_test/20220509_compile_preprocessing_test]4# gcc -E test.c -o test.i [root@ubuntu /arnold_test/20220509_compile_preprocessing_test]5# [root@ubuntu /arnold_test/20220509_compile_preprocessing_test]5# [root@ubuntu /arnold_test/20220509_compile_preprocessing_test]5# cat test.i # 1 "test.c" # 1 "测试2(测试简单的宏替换)" # 1 " " # 1 "/usr/include/stdc-predef.h" 1 3 4 # 1 " " 2 # 1 "test.c" int main(){ (time)(NULL); return 0; } [root@ubuntu /arnold_test/20220509_compile_preprocessing_test]6#
ubuntu上
#define KY_print printf
int main(){
KY_print("I miss un");
return 0;
}
预处理:
[root@ubuntu /arnold_test/20220509_compile_preprocessing_test]8# gcc -E test.c # 1 "test.c" # 1 "来看两个花括号测试(花括号能隔离环境)" # 1 " " # 1 "/usr/include/stdc-predef.h" 1 3 4 # 1 " " 2 # 1 "test.c" int main(){ printf("I miss un"); return 0; }
参考文章:c语言加花括号的原则
ubuntu上
测试1#pragma warning(disable : 4996) #include#include int main() { int a = 1; { int a = 2; printf("%dn", a); //2 } printf("%dn", a); //1 return 0; }
ubuntu上
测试2#pragma warning(disable : 4996) #include测试宏函数(visual studio vc 无法使用复合语句表达式 ({}))#include int main() { int a = 1; { a = 2; printf("%dn", a); //2 } printf("%dn", a); //2 return 0; }
ubuntu上
//#pragma warning(disable : 4996) #include#include #define PLUS ({int a = 1; int b =2; (a+b);}) int main() { printf("%un", PLUS); return 0; }
vs上代码检查就报错了,啥情况呢?
上面的语法其实是gnu的复合语句表达式
示例1(在复合表达式中定义函数,调用函数,判断语句,以最后一个语句的值作为返回)1、⼀对圆括号在外边,⼀对⼤括号在⾥⾯。
2、复合语句可以有函数调⽤、变量赋值
3、最后⼀条语句必须以分号结尾。
4、最后⼀条语句的值,将作为整个表达式的值
5、如果你在⼤括号⾥的最后⼀句⽤的是没有返回值的语句,则整个表达式的返回类型为 void,即没有合法的返回值
参考文章:C语言的复合语句表达式
//#pragma warning(disable : 4996) #include#include int main() { int a = ({ int foo() { return 10; } int y =foo(); int z; if(y > 0) z = y; else z =-y; z; }); printf("%dn", a); return 0; }
同样,猜测({})也能隔绝环境,没测试哈。。。
比较复杂的宏语句,以后再更。。。 参考文章参考文章:C语言(复合语句表达式)



