3

I am new in c programming, and I am trying to understand the sizeof function.

Please help me understand how this program works:

#include<stdio.h>
main( )
{
    printf ( "\n%d %d %d", sizeof ( '3'), sizeof ( "3" ), sizeof ( 3 ) ) ;
}

I am getting output as 4 2 4.

However, I am not able to understand the reason I get this output. Kindly explain it.

Jordan
  • 6,083
  • 3
  • 23
  • 30
best wishes
  • 5,789
  • 1
  • 34
  • 59

2 Answers2

9
  1. sizeof ( '3'), it is the size of character constant which is int so you are getting value as 4 on your machine.

  2. sizeof ( "3" ), it is size of string i.e. 2.
    String "3" is made of 2 character ('3'+'\0') = "3". And we knowsizeof(char) is 1.

  3. sizeof ( 3 ), it is size of int which is 4 on your machine.

ani627
  • 5,578
  • 8
  • 39
  • 45
9

First off, a couple of notes:

Onto your question.

  • In the comp.lang.c FAQ, question 8.9 explains that character constants in C are of type int, so sizeof('3') is sizeof(int) (which appears to be 4 on your machine.)
  • When applied to arrays, sizeof returns the size of the array in bytes. For example, sizeof(int[10]) returns 40 on a machine where sizeof(int) is 4. Since sizeof(char) is 1, it will equal the amount of characters in a string literal. As explained by Jonathan Leffler:

    1. sizeof("f") must return 2, one for the 'f' and one for the terminating '\0'.

    2. [...]

    The string literal has the type 'array of size N of char' where N includes the terminal null.

    Remember, arrays do not decay1 to pointers when passed to sizeof.

    1 Exception to array not decaying into a pointer?

  • And lastly, sizeof(3) is sizeof(int).
Community
  • 1
  • 1