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

后端 未结 6 1420
醉梦人生
醉梦人生 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-09 12:55

    Any single-valued literal is a constant expression.

    3     0.0f    '\n'
    

    (String literals are weird, because they're actually arrays. Seems "hello" isn't really a constant, as it ends up having to be linked and all that, and the address and contents can change at runtime.)

    Most operators (sizeof, casts, etc) applied to constants or types are constant expressions.

    sizeof(char)
    (byte) 15
    

    Any expression involving only constant expressions is itself also a constant expression.

    15 + 3
    0.0f + 0.0f
    sizeof(char)
    

    Any expression involving function calls or non-constant expressions is usually not a constant expression.

    strlen("hello")
    fifteen + x
    

    Any macro's status as a constant expression depends on what it expands to.

    /* Always a constant */
    #define FIFTEEN 15
    
    /* Only constant if (x) is
    #define htons(x)  (( ((x) >> 8) | ((x) << 8) ) & 0xffff) 
    
    /* Never constant */
    #define X_LENGTH  strlen(x)
    

    I originally had some stuff in here about const identifiers, but i tested that and apparently it doesn't apply in C. const, oddly enough, doesn't declare constants (at least, not ones "constant" enough to be used in switch statements). In C++, however, it does.

提交回复
热议问题