Size of Char in C

Hello,

I ran the following code in Visual C++ and I have 1 and 4
In GCC 11.2 I have 1 and 1

Why in Visual C++ do we have 4 for a character?

Thank you

1
2
3
 char c = '\0';
    printf("    sizeof c = %2zu\t       sizeof(char) = %2zu\n",
        sizeof c, sizeof('A'));
> sizeof('A')
It's one of the many differences between C and C++.
In C, this is the size of an integer, but in C++ it is the size of a character.
http://david.tribble.com/text/cdiffs.htm#C99-char-literal

Be mindful of whether you compile your test as C or C++.
Yeah, char literals in C have type int.

Just look at all the <ctype.h>/<cctype> functions such as tolower, isspace, etc. They all take an int as argument.

The type is less important in C because there is no function overloading and the promotion rules will automatically convert chars to ints when passing them to for example printf.
Last edited on
There may, back in the day, have been hardware reasons too. Some of the older cpus worked better with fixed sized chunks, the machine's 'word' size. This is a dim memory, not sure to be honest, but it was similar to how structs can be realigned by some compilers for performance reasons.
Why in Visual C++ do we have 4 for a character?

Microsoft.

Well, to be less flippant....

different C/C++ implementations, possible different data type sizes.

As others have pointed out, what A' is treated as being -- char/int -- differs.
Not in VS C++ you don't. It's a char.

Compiled as C++:

1
2
3
4
5
6
7
8
#include <cstdio>

int main() {
	char c = '\0';

	printf("    sizeof c = %2zu\t       sizeof(char) = %2zu\n",
		sizeof c, sizeof('A'));
}



    sizeof c =  1              sizeof(char) =  1


But compiled as C code:


    sizeof c =  1              sizeof(char) =  4


But, as has been pointed out above, in C a char literal (eg 'A') has a type of int, not char. That's why in C sizeof('A') is 4 and not 1. The output is misleading as it's not showing sizeof(char), but sizeof (char_literal). In C++ they are the same. In C they are not.

Last edited on
sizeof(char) is always 1.
Last edited on
Topic archived. No new replies allowed.