Why are C character literals ints instead of chars?

后端 未结 12 865
悲哀的现实
悲哀的现实 2020-11-22 02:24

In C++, sizeof(\'a\') == sizeof(char) == 1. This makes intuitive sense, since \'a\' is a character literal, and sizeof(char) == 1 as d

12条回答
  •  不知归路
    2020-11-22 02:54

    This is the correct behavior, called "integral promotion". It can happen in other cases too (mainly binary operators, if I remember correctly).

    EDIT: Just to be sure, I checked my copy of Expert C Programming: Deep Secrets, and I confirmed that a char literal does not start with a type int. It is initially of type char but when it is used in an expression, it is promoted to an int. The following is quoted from the book:

    Character literals have type int and they get there by following the rules for promotion from type char. This is too briefly covered in K&R 1, on page 39 where it says:

    Every char in an expression is converted into an int....Notice that all float's in an expression are converted to double....Since a function argument is an expression, type conversions also take place when arguments are passed to functions: in particular, char and short become int, float becomes double.

提交回复
热议问题