Operator 'sizeof' with conditional (ternary) expression

后端 未结 3 440
野的像风
野的像风 2021-01-17 10:53

I have a hard time understanding sizeof\'s behaviour when given a ternary expression.

#define STRING \"a s         


        
3条回答
  •  孤城傲影
    2021-01-17 11:22

    You need to understand that sizeof is entirely a compile-time operator. With VLA it could return a variable expression, otherwise it is a compile-time constant.

    What matters is the type of its argument.

    So in sizeof(argc > 1 ? STRING : "") the condition is not evaluated. The type of the argument is decayed to const char*. And on your machine, it is 4.

    You should code instead (argc > 1)?sizeof(STRING):1

    Since STRING is macro-expanded to the "a string" literal, sizeof(STRING) is 9, nearly as if you have declared

    const char STRING[] = {'a',' ','s','t','r','i','n','g','\0'};
    

提交回复
热议问题