In C the following code:
#include<stdio.h>
int main()
{
char c='a';
printf("%d %d",sizeof(c),sizeof('a'));
return 0;
}
produces the result 1
and 4
? Please explain the logic?
Also, why does sizeof(main())
result in 4
but sizeof(main)
results in 1
:
#include<stdio.h>
int main()
{
printf("%d %d\n",sizeof(main), sizeof(main()));
return 0;
}
And in C++ why does sizeof('a')
result in 1 but sizeof('av') results in 4?
Character constants in C are of type int, although this is not the case in C++. From the draft C99 standard section 6.4.4.4
Character constants paragraph 10 says (emphasis mine):
An integer character constant has type int. The value of an integer character constant containing a single character that maps to a single-byte execution character is the numerical value of the representation of the mapped character interpreted as an integer. The value of an integer character constant containing more than one character (e.g., 'ab')[...]
from the draft C++ standard section 2.14.3
Character literals paragraph 1 says (emphasis mine):
[...]An ordinary character literal that contains a single c-char representable in the execution character set has type char,[...] An ordinary character literal that contains more than one c-char is a multicharacter literal. A multicharacter literal, or an ordinary character literal containing a single c-char not representable in the execution character set, is conditionally-supported, has type int, and has an implementation-defined value.
So av
is a multicharacter literal and will have size of int.
For the second part of the question, sizeof(main)
is not valid code, although compiler may choose to still produce a result it will be implementation defined, from the draft C99 standard section 6.5.3.4
The sizeof operator paragraph 1 says:
The sizeof operator shall not be applied to an expression that has function type or an incomplete type, [...]
the draft C++ standard has similar wording and both gcc
and clang
warn about this code when using the -pedantic
flag, with an error like this:
warning: invalid application of 'sizeof' to a function type [-pedantic]
for sizeof(main())
since sizeof
is a compile time operator and does not evaluate it's arguments except in the case of variable length arrays the result is the size of the return type which is int in this case. For example we can see live example:
long double func()
{
return 1.0 ;
}
that sizeof(func())
returns 16
.
Note
On your platform sizeof(int)
is 4
but the size is implementation defined.
Note 2
Since the result of sizeof
is size_t a more portable format specifier for printf
would be %zu
.
Character constants are int
s not char
s. So 'a'
is stored in 4 bytes, than when stored in c
, it is shortened to 1 to become a char
.
Note that technically this size of int
s are implementation dependent.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With