简体   繁体   中英

GCC __builtin_constant_p always returning 0

I have the following code:

const int a = 10;
int b = __builtin_constant_p(a);
printf("%d\n", b);

output is 0. I read the man, the value of 0 doesn't mean that a is not a compile time constant , just that gcc can't prove that it is. Anyway I can get this output to be 1?

A const -qualified variable is not a constant expression in C, but GCC does not document __builtin_constant_p as determining if the argument is a constant expression anyway. Rather, it's documented to "determine if a value is known to be constant at compile time and hence that GCC can perform constant-folding on expressions involving that value". So it should be usable for what you want.

The problem is almost certainly just that you compiled with -O0 (no optimization, the default), in which case no constant-folding can take place because you have it turned off. Turn on optimization (at least -O1 , but normally you want -O2 or -Os ) and it should do what you want.

A variable is never a constant (unless constant folding is used, but you have to have optimization enabled for that), even if it is const -qualified.

__builtin_constant_p will return true for a constant only. For example:

int b = __builtin_constant_p(10);
printf("%d\n", b);

will print 1 .

Note that your code will print 1 also if you compile with optimization enabled ( -O at minimum, but any other legal -O flag will work except for -O0 ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM