Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sizeof vs sizeof() in standard C? [duplicate]

Tags:

c

sizeof

I saw some code which used sizeof directly and wondered if it is standard C. To my surprise, it was working just fine. Here is an example:

#include <stdio.h>
#include <string.h>

int main()
{
   char buff[255];
   printf("size %d\n", sizeof buff);
   return 0;
}

Output: size 255

As you can see, in the above example I used sizeof <variable> instead of sizeof(<variable>)

Please throw more light on it.

like image 589
Sandeep Avatar asked Oct 30 '14 12:10

Sandeep


People also ask

What can I use instead of sizeof in C?

No there is not alternative to sizeof() operator in standard ANSI C. Sizeof() is a compiletime operator can be applied to type too ,i.e. sizeof(int); runtime not call any function so sizeof() is very quick.

What is sizeof () in C?

Sizeof is a much used operator in the C or C++. It is a compile time unary operator which can be used to compute the size of its operand. The result of sizeof is of unsigned integral type which is usually denoted by size_t.

Can you call sizeof on a variable?

It returns the size of a variable. It can be applied to any data type, float type, pointer type variables. When sizeof() is used with the data types, it simply returns the amount of memory allocated to that data type.


1 Answers

"When sizeof's operand is a type, it has to be enclosed in parentheses. But when sizeof's operand is a variable, this is not required."--Expert C Programming: Deep C secrets. And from c11 standard:

sizeof unary-expression
sizeof ( type-name )
like image 135
Yulong Ao Avatar answered Sep 19 '22 09:09

Yulong Ao