我偶然发现了一段奇怪的代码,我认为它不会像预期的那样工作,但确实如此。例如:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
printf("%d\n", abs(-1)); // output: 1
printf("%d\n", (abs)(-1)); // output: 1
return 0;
}
显然在函数调用中将括号括在函数名称周围对程序没有影响。它只是让它看起来像一个演员。
如果以某种方式定义,我有点兴趣。但我认为它并没有被禁止,这就是它起作用的原因。
我真正感到好奇的是,是否存在这种符号可能会产生任何优势的情况? (代码结构,可读性,任何可能有用的东西)
或者编写代码只是一种“奇怪”的方式吗?
答案 0 :(得分:3)
尝试
int foo(int a, int b) { return a+b; }
#define foo(a,b) ((a)+(b)+1)
#include <stdio.h>
int main() {
printf("%d %d\n",
foo(3, 5), // Use macro if defined
(foo)(3, 5) // Always call function even if there's a macro
);
return 0;
}
输出:
9 8
看到区别?