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;
What is the type of integer literal -1 and 2 and -2, and how does it get converted to get stored in signed int and unsigned int?
What is meant by signed integer, is that the property of variable or integer literal too? Like -2 is signed integer and 2 is unsigned integer?
First off,
-1is not an integer constant. It's an expression consisting of a unary-operator applied to the constant1.In C99 and C11, the type of a decimal integer constant is the first of
int,long int, orlong long intin which its value will fit. Similarly, an octal or hexadecimal literal has typeint,unsigned int,long int,unsigned long int,long long int, orunsigned long long int. The details are in N1570 6.4.4.1.-1and-2are constant expressions. The result of the unary-operator has the same type as the operand (even if that result causes an overflow, as-INT_MINdoes in most implementations).The constant
1and the expression-1are both of typeint. The value is stored in theintobjecti; no conversion is necessary. (Strictly speaking, it's converted frominttoint, but that doesn't matter.)2is of typeint. It's converted frominttounsigned int.-2is of typeint. It's converted frominttounsigned int. This time, because-2is outside the range ofunsigned int, the conversion is non-trivial; the result isUINT_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
1and0xff.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
-1and2+2.