Why does “sizeof(a ? true : false)” give an output of four bytes?

后端 未结 7 1556
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-30 07:41

I have a small piece of code about the sizeof operator with the ternary operator:

#include 
#include 

int main()
{
         


        
7条回答
  •  北荒
    北荒 (楼主)
    2021-01-30 08:28

    Here, ternary operator return boolean type,

    OK, there's more to that!

    In C, the result of this ternary operation is of type int. [notes below (1,2)]

    Hence the result is the same as the expression sizeof(int), on your platform.


    Note 1: Quoting C11, chapter §7.18, Boolean type and values

    [....] The remaining three macros are suitable for use in #if preprocessing directives. They are

    true

    which expands to the integer constant 1,

    false

    which expands to the integer constant 0, [....]

    Note 2: For conditional operator, chapter §6.5.15, (emphasis mine)

    The first operand is evaluated; there is a sequence point between its evaluation and the evaluation of the second or third operand (whichever is evaluated). The second operand is evaluated only if the first compares unequal to 0; the third operand is evaluated only if the first compares equal to 0; the result is the value of the second or third operand (whichever is evaluated), [...]

    and

    If both the second and third operands have arithmetic type, the result type that would be determined by the usual arithmetic conversions, were they applied to those two operands, is the type of the result. [....]

    hence, the result will be of type integer and because of the value range, the constants are precisely of type int.

    That said, a generic advice, int main() should better be int main (void) to be truly standard-conforming.

提交回复
热议问题