patterncppCritical
Why is the size of a character sizeof('a') different in C and C++?
Viewed 0 times
sizeofdifferentwhyandthecharactersize
Problem
#include
int main(void)
{
printf("sizeof(char) = %zu\n", sizeof(char));
printf("sizeof('a') = %zu\n", sizeof('a'));
}See https://godbolt.org/z/1eThqvMhx
When running this code in C, it prints
sizeof(char) = 1
sizeof('a') = 4When running this code in C++, it prints
sizeof(char) = 1
sizeof('a') = 1Why does the output differ between languages?
What is the size of a character in C and C++? As far as I know, the size of
char is 1 byte in both C and C++.Solution
In C, the type of a character constant like
'a' is actually an int, with size of 4 (or some other implementation-dependent value). In C++, the type is char, with size of 1. This is one of many small differences between the two languages.Context
Stack Overflow Q#2172943, score: 410
Revisions (0)
No revisions yet.