Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should we use sizeof with and without parentheses [duplicate]

Tags:

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 is: 36

size is: 36

But when should we use sizeof with and without parentheses?

like image 500
cmidi Avatar asked Jan 21 '15 19:01

cmidi


People also ask

Does sizeof need parentheses?

To use sizeof with a type name, the name must be enclosed in parentheses. An expression.

Why is sizeof an operator?

Because it is a compile-time operator that, in order to calculate the size of an object, requires type information that is only available at compile-time. This doesn't hold for C++. Show activity on this post. sizeof() operator is a compile time would be occurrence.


1 Answers

When using sizeof with a type, you need parentheses around the type. When using it with an expression, you don't. But you can of course include them in this case as well, and you don't have to worry about operator precedence in such case. With uncommon operators such as this one, fewer people would be sure of the precedence, so clarity certainly helps.

So I'd say it's preferable to use them always.

like image 56
Angew is no longer proud of SO Avatar answered Sep 25 '22 11:09

Angew is no longer proud of SO