When should we use sizeof with and without parentheses

typedef struct rem{ int addr; char addrbuf[32]; } foo; 

Both of these codes return the same results.

 foo addr; printf("size is: %d\n",sizeof addr); printf("size is: %d\n",sizeof (foo)); 

size: 36

size: 36

But when should we use sizeof with and without parentheses?

+6
source share
2 answers

When using sizeof with a type, you need parentheses around the type. When using this expression, you do not. But you can, of course, turn them on in this case too, and you don’t need to worry about the priority of the operator in this case. With unusual operators such as this one, fewer people will be sure of priority, so clarity certainly helps.

Therefore, I would say that it is better to use them always.

+14
source

[expr.sizeof] / 1:

An operand is either an expression that is an unvalued operand (Section 5) or with a type index .

Thus, brackets are only required for types. If you prefer to use parentheses for clarity and consistency (like me), you can always use them since the parentheses around the expression form a different expression.
The priority of the sizeof operator is not well known and can be annoying.

Also, for the sizeof... operator sizeof... you always need to use parentheses (another reason for consistency).

+10
source

Source: https://habr.com/ru/post/981362/


All Articles