Friday, 29 March 2013

C/C++ Puzzles: PART - 32

The sizeof character literal in C/C++

  Consider the C Program given below. 

#include<stdio.h>

int main()
{
    printf("\nSize of char is %d\n",sizeof(char));
    printf("\nSize of char 'a' is %d\n",sizeof('a'));
    return 0;
}


Figure Below Shows the Output

Now consider the case where the same code being executed as a C++ Program. The Program and Output is shown below.

include<stdio.h>

using namespace std;

int main()
{
  printf("\nSize of char is %d\n",sizeof(char));
  printf("\nSize of char 'a' is %d\n",sizeof('a'));
  return 0;
}


Figure Below Shows the Output

The same program gives different output when executed as C and C++ Programs. Why? This is because of a minor difference between C and C++. In C a character literal like 'a' is treated as an int, hence the size is 4 Byte. Whereas in C++ character literals are treated as characters and the size is just 1 Byte.

No comments:

Post a Comment