What Are Integer Literal Type? And How They Are Stored?

后端 未结 4 1367
逝去的感伤
逝去的感伤 2020-12-21 17:44

I have just started learning C and a question has bugged me for a while now. If I write

int i = -1;
unsigned int j = 2;
unsigned int k = -2;
<
4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-21 17:51

    First off, -1 is not an integer constant. It's an expression consisting of a unary - operator applied to the constant 1.

    In C99 and C11, the type of a decimal integer constant is the first of int, long int, or long long int in which its value will fit. Similarly, an octal or hexadecimal literal has type int, unsigned int, long int, unsigned long int, long long int, or unsigned long long int. The details are in N1570 6.4.4.1.

    -1 and -2 are constant expressions. The result of the unary - operator has the same type as the operand (even if that result causes an overflow, as -INT_MIN does in most implementations).

    int i = -1;
    

    The constant 1 and the expression -1 are both of type int. The value is stored in the int object i; no conversion is necessary. (Strictly speaking, it's converted from int to int, but that doesn't matter.)

    unsigned int j = 2;
    

    2 is of type int. It's converted from int to unsigned int.

    unsigned int k = -2;
    

    -2 is of type int. It's converted from int to unsigned int. This time, because -2 is outside the range of unsigned int, the conversion is non-trivial; the result is UINT_MAX - 1.

    Some terminology:

    A constant is what some other languages call a literal. It's a single token that represents a constant value. Examples are 1 and 0xff.

    A constant expression is an expression that's required to be evaluated at compile time. A constant is a constant expression; so is an expression whose operands are constants or constant expressions. Examples are -1 and 2+2.

提交回复
热议问题