3
#include<stdio.h>
int main()
{
printf("\nsize of int : %d", sizeof int);
return 0;
}

is returning error

error: expected expression before ‘int’ 

while compiling with C and

expected primary-expression before ‘int’

while compiling with C++, but the following codes works just fine.

#include<stdio.h>
int main()
{
int b;
printf("\nsize of int : %d", sizeof b);
;
return 0;
}

Why is it so? What is the difference in both the cases?

tinutomson
  • 329
  • 6
  • 12
  • I know it works with a (). I dont understand why it does not work without one. – tinutomson Apr 03 '14 at 12:36
  • As far as I can tell, it doesn't get much better than "because the standard says so", unfortunately. For example, C99 lists `sizeof unary-expression` and `sizeof ( type-name )`. – chris Apr 03 '14 at 12:38
  • [6.5.3.4 The sizeof operator](http://c0x.coding-guidelines.com/6.5.3.4.html) – Grijesh Chauhan Apr 03 '14 at 12:40
  • possible duplicate of [Why sizeof int is wrong, while sizeof(int) is right?](http://stackoverflow.com/questions/13120473/why-sizeof-int-is-wrong-while-sizeofint-is-right) – alk Apr 03 '14 at 13:49

3 Answers3

12

sizeof needs parentheses when used with a type. They're optional with an expression.

Your code would then become:

printf("\nsize of int : %zu", sizeof(int));

Thanks to @Grijesh, I've also used the right format specifier for size_t. If this format specifier causes problems (likely related to Windows), the next best would probably be %lu.

chris
  • 60,560
  • 13
  • 143
  • 205
3

You forgot the brackets(). When you are using sizeof with a type you need brackets. Try this:

printf("\nsize of int : %zu", sizeof(int));

You may also use the format specifier %lu when %zu is not available in microsoft compilers.

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
1

The sizeof operator is used to determine the amount of space a designated datatype would occupy in memory. To use sizeof, the keyword "sizeof" is followed by a type name or an expression (which may be merely a variable name). If a type name is used, it must always be enclosed in parentheses, whereas expressions can be specified with or without parentheses.

char c;

printf("%zu,%zu\n", sizeof c, sizeof (int));
Srikanth
  • 131
  • 8