要检查的示例代码
#include<stdio.h>
int main(void)
{
const int i = 1;
printf("Variable i is %s\n",
__builtin_constant_p(i) ? "a const variable" : "not a const variable");
return 0;
}
输出:
Variable i is not a const variable
__builtin_constant_p()
不是确定变量是否为const
类型的正确API吗?
答案 0 :(得分:5)
您可以使用通用选择(自C11起):
#include <stdio.h>
#define __is_constant_int(X) _Generic((&X), \
const int *: "a const int", \
int *: "a non-const int")
int main(void)
{
const int i = 1;
printf("Variable i is %s\n", __is_constant_int(i));
return 0;
}