Know if const qualifier is used

后端 未结 4 1605
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-19 13:46

Is there any way in C to find if a variable has the const qualifier? Or if it\'s stored in the .rodata section?

For example, if I have this function:



        
4条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-19 14:22

    GCC provides the __builtin_constant_p builtin function, which enables you to determine whether an expression is constant or not at compile-time:

    Built-in Function: int __builtin_constant_p (exp)

    You can use the built-in function __builtin_constant_p 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. The argument of the function is the value to test. The function returns the integer 1 if the argument is known to be a compile-time constant and 0 if it is not known to be a compile-time constant. A return of 0 does not indicate that the value is not a constant, but merely that GCC cannot prove it is a constant with the specified value of the `-O' option.

    So I guess you should rewrite your foo function as a macro in such a case:

    #define foo(x) \
      (__builtin_constant_p(x) ? foo_on_const(x) : foo_on_var(x))
    

    foo("abc") would expand to foo_on_const("abc") and foo(str) would expand to foo_on_var(str).

提交回复
热议问题