1

When I ran this program it gave an output of

1, 4, 4

Why does sizeof('A') gives 4 bytes? Is 'A' treated as integer? If so, then why?

#include<stdio.h>

int main()
{
char ch = 'A';
printf("%d, %d, %d", sizeof(ch), sizeof('A'), sizeof(3.14f));
return 0;
}

Moreover, when I replace

printf("%d, %d, %d", sizeof(ch), sizeof('A'), sizeof(3.14f));

with,

printf("%d, %d, %d", sizeof(ch), sizeof("A"), sizeof(3.14f));

It gives the output

1, 2, 4

which is even more confounding.

P.S.: I used compileonline.com to test this code.

3 Answers3

4

In C, the type of 'A' is int, which explains why sizeof('A') is 4 (since evidently your platform has 32-bit int). For more information, see Size of character ('a') in C/C++

When compiled as C++, the first program prints 1 1 4.

"A" is a string literal consisting of the letter A followed by the NUL character. Since it's two characters long, sizeof("A") is 2.

Community
  • 1
  • 1
NPE
  • 486,780
  • 108
  • 951
  • 1,012
1

1.sizeof operator provide the size of input argument.
2.Size of a vaiable is machine(complier) dependent.In you case it is 32 bit.
3.sizeof(ch)=1 because you declare as char.
4.sizeof('A')=4 because compiler treats the literal constant as an integer.
5.sizeof("A")=2 because its a string of 2 bye.In the case string,if u write a single character also compiler insert null character at the end.so its size is 2 bytes.
4.sizeof(3.13f)=4 because its size of float is 4 bytes

Rajdhar
  • 332
  • 1
  • 4
  • 10
0

I generally suggest to use sizeof on types or on variables. Using sizeof on literal constants seems confusing (except perhaps on literal strings, to compute 1 + their string length at compile time).

The literal 'A' is in C an int whose size is 4 on your machine.

The literal string "A" is exactly like

   const char literal_A_string[] = {'A', (char)0};

whose size is obviously 2 bytes (because each literal string has a terminal null byte appended).

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547