Char Size. The size of both unsigned and signed char is 1 byte always, irrespective of what compiler we use.
'a' by default is an integer and because of that you get size of int in your machine 4 bytes.
Answer:In C++ the size of the character literal is char. So in C the sizeof('a') is 4 for 32bit architecture, and CHAR_BIT is 8. ... But the sizeof(char) is one byte for both C and C++.
%s and %c are not formats or types. They are called "conversion or format specifiers", used for the correct formatting regarding one of the character types or a string, used by functions of the printf() and scanf() families. Thus, they have no "size" or "range" on their own.
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.
As Paul stated, it's because 'a'
is an int
in C but a char
in C++.
I cover that specific difference between C and C++ in something I wrote a few years ago, at: http://david.tribble.com/text/cdiffs.htm
In C the type of character literals are int and char in C++. This is in C++ required to support function overloading. See this example:
void foo(char c)
{
puts("char");
}
void foo(int i)
{
puts("int");
}
int main()
{
foo('i');
return 0;
}
Output:
char
In C language, character literal is not a char
type. C considers character literal as integer. So, there is no difference between sizeof('a')
and sizeof(1)
.
So, the sizeof character literal is equal to sizeof integer in C.
In C++ language, character literal is type of char
. The cppreference say's:
1) narrow character literal or ordinary character literal, e.g.
'a'
or'\n'
or'\13'
. Such literal has typechar
and the value equal to the representation of c-char in the execution character set. If c-char is not representable as a single byte in the execution character set, the literal has type int and implementation-defined value.
So, in C++ character literal is a type of char
. so, size of character literal in C++ is one byte.
Alos, In your programs, you have used wrong format specifier for sizeof
operator.
C11 §7.21.6.1 (P9) :
If a conversion specification is invalid, the behavior is undefined.275) If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.
So, you should use %zu
format specifier instead of %d
, otherwise it is undefined behaviour in C.
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