Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Size of character ('a') in C/C++

Tags:

c++

c

types

People also ask

What is the size of a character in C?

Char Size. The size of both unsigned and signed char is 1 byte always, irrespective of what compiler we use.

Why sizeof (' a ') is 4 in C?

'a' by default is an integer and because of that you get size of int in your machine 4 bytes.

What will sizeof a return char a []=?

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++.

What is the size of %s in 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 type char 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.