什么是整数文字类型?它们是如何存储的? [英] What are integer literal types? And how are they stored?
问题描述
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 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
.
这篇关于什么是整数文字类型?它们是如何存储的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!