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,
-1
is 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 int
in 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.-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).The constant
1
and the expression-1
are both of typeint
. The value is stored in theint
objecti
; no conversion is necessary. (Strictly speaking, it's converted fromint
toint
, but that doesn't matter.)2
is of typeint
. It's converted fromint
tounsigned int
.-2
is of typeint
. It's converted fromint
tounsigned int
. This time, because-2
is 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
1
and0xff
.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
and2+2
.