Why sizeof int is wrong, while sizeof(int) is right?

前端 未结 3 804
甜味超标
甜味超标 2020-12-02 08:58

We know that sizeof is an operator used for calculating the size of any datatype and expression, and when the operand is an expression, the parentheses can be o

3条回答
  •  一个人的身影
    2020-12-02 09:25

    There are two ways to use the sizeof operator in C. The syntax is this:

    C11 6.5.3 Unary operators
    ...
    sizeof unary-expression
    sizeof ( type-name )
    

    Whenever you use a type as operand, you must have the parenthesis, by the syntax definition of the language. If you use sizeof on an expression, you don't need the parenthesis.

    The C standard gives one such example of where you might want to use it on an expression:

    sizeof array / sizeof array[0]
    

    However, for the sake of consistency, and to avoid bugs related to operator precedence, I would personally advise to always use () no matter the situation.

提交回复
热议问题