Example of something which is, and is not, a “Constant Expression” in C?

后端 未结 6 1413
醉梦人生
醉梦人生 2020-12-09 11:54

I\'m a tad confused between what is and is not a Constant Expression in C, even after much Googleing. Could you provide an example of something which is, and which is not, a

6条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-09 12:55

    There is another subtlety to constant expressions. There are some things that are known to the compiler, but cannot be known to the preprocessor.

    For example (24*60*60) can be computed by both, but sizeof struct foo is only known to the compiler. This distinction can matter if you are trying to verify that a struct is defined to meet an externally mandated size, or that its members are mapped at externally specified offsets. (This use case often arises when coding device drivers where the struct describes device registers as layed out in memory space.)

    In that instance you cannot simply say #if (sizeof(struct UART) == 12) because the preprocessor operates at a pass ahead of the compilation and simply cannot know the size of any types. It is, however, a constant expression and would be valid as an initializer for a global variable (e.g. int UARTwords = sizeof(struct UART) / sizeof(short);), or to declare the size of an array (e.g. unsigned char UARTmirror[sizeof(struct UART)];)

提交回复
热议问题