int main(void) { const int i = 1; printf("Variab...">

How to check if a variable of type "const" in C matches?

Sample code to verify

#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; } 

Output:

 Variable i is not a const variable 

Is __builtin_constant_p() not a valid API to determine if a variable is of type const or not?

+5
source share
2 answers

You can use the general selection (starting with 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; } 
+5
source

RTFineManual :

You can use the __builtin_constant_p built-in function to determine if a constant value is known at compile time ... "

(emphasis mine) Please note that this is a gcc compiler extension, so it does not comply with the standard.

C has no symbolic constants other than enum constants. const qualified objects are still variables. Thus, the test fails. See the manual for a typical application.


Notes:

Assuming the above code is just an example, your question looks like an XY problem. C is statically typed, so at the point where you use this construct, the full type is well known. The only way to have something like a function is with a macro. But hiding different behaviors in a macro will cause confusion for the code reader. She must remember this difference for each involution.

Instead, use two functions with different behaviors and name them accordingly. Since the caller knows the type, he can use the correct function, and any code reader (including you in a few weeks!) Will immediately know the difference.

+3
source

Source: https://habr.com/ru/post/1246988/


All Articles