Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C preprocessor macros - definition vs. value portability & practice

For compiler-specific code, it's common to see cpp directives such as:

#if defined (__GNUC__) && (__GNUC__ >= 4)

which is the preprocessor test I typically use - not exclusively for __GNUC__, but it's a common example. Alternatively,

#if (__GNUC__ >= 4)

appears to satisfy the same requirements. Are there potential problems with the latter? Not only with gcc, but any standards-conforming preprocessor. Can the LHS be evaluated as a certain value, even if it's not defined? Are there any pitfalls to the second approach that any language lawyers are aware of?

like image 929
Brett Hale Avatar asked Mar 10 '12 07:03

Brett Hale


1 Answers

The preprocessor assumes undefined macros to have the value 0 in comparisons, so your simplification is ok in this case. If you want to check against a lower version than 4 in gcc, you may get into trouble though since it would evaluate as true with a < even if it's not gcc.

I think the reason for using both is also a question of understandability, if you check

#if defined(__GNUC__) && (__GNUC>=4)

it's rather obvious you're not already in a block with code that only is for GCC, while the simplification

#if (__GNUC__ >= 4)

does not make that obvious and can be read as a version check only when you already know it's gcc.

like image 81
Joachim Isaksson Avatar answered Nov 15 '22 09:11

Joachim Isaksson