Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does sizeof without () do? [duplicate]

Tags:

c

sizeof

The author of this question just made fun on me when I asked him what sizeof * q does... He told me that's a really basic C question and I should check it out. But as I looked around on SO and haven't seen some one asking before, I'll do it now by my self:

What does sizeof in C do when it is used without parentheses and/or type?

like image 252
dhein Avatar asked Sep 19 '13 15:09

dhein


People also ask

What is the use of sizeof () operator?

You can use the sizeof operator to determine the size that a data type represents. For example: sizeof(int); The sizeof operator applied to a type name yields the amount of memory that can be used by an object of that type, including any internal or trailing padding.

Why is sizeof () an operator and not a function?

sizeof operator is compile time entity not runtime and don't need parenthesis like a function. When code is compiled then it replace the value with the size of that variable at compile time but in function after function gets execute then we will know the returning value.

What is the use of sizeof () method explain with example?

Need of sizeof() operator Mainly, programs know the storage size of the primitive data types. Though the storage size of the data type is constant, it varies when implemented in different platforms. For example, we dynamically allocate the array space by using sizeof() operator: int *ptr=malloc(10*sizeof(int));

Why sizeof int is false?

sizeof(int) > (unsigned int)-1 is false, because (unsigned int)-1 is a very large number on most implementations (equal to UINT_MAX, or the largest number which fits in an unsigned int ).


1 Answers

So if we look at the grammar for sizeof in the C99 draft standard section 6.5.3 Unary operators paragraph 1 it is as follows:

sizeof unary-expression
sizeof ( type-name )

There is a difference you can not use a type-name without parenthesizes and section 6.5.3.4 The sizeof operator paragraph 2 says(emphasis mine):

The sizeof operator yields the size (in bytes) of its operand, which may be an expression or the parenthesized name of a type.[...]

For completeness sake you may wonder if we can use sizeof with an expression if we have parenthesizes and the answer is yes since a unary-expression can itself contain parenthesizes. The easiest way to see this would be to look section A.2.1 Expressions from the draft standard and work through the grammar like so:

unary-expression -> postfix-expression -> primary-expression -> ( expression )
like image 145
Shafik Yaghmour Avatar answered Nov 11 '22 22:11

Shafik Yaghmour