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

前端 未结 4 1324
天命终不由人
天命终不由人 2020-11-22 03:08

What is the size of character in C and C++ ? As far as I know the size of char is 1 byte in both C and C++.

In C:

#include 

        
4条回答
  •  傲寒
    傲寒 (楼主)
    2020-11-22 03:28

    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.

提交回复
热议问题