什么是整数文字类型?以及它们如何存储? [英] What Are Integer Literal Type? And How They Are Stored?
问题描述
我刚刚开始学习C,现在有一个问题困扰了我一段时间。如果我写
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;
整数常量 -1
和 2
和 -2
,以及如何将其转换为存储在 signed中int
和 unsigned int
?
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
?
带符号整数是什么意思,变量或整数文字的属性也是吗?像 -2
是有符号整数而 2
是无符号整数吗?
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?
推荐答案
首先, -1
不是整数常量。该表达式由应用于常量 1
的一元-
运算符组成。
First off, -1
is not an integer constant. It's an expression consisting of a unary -
operator applied to the constant 1
.
在C99和C11中,十进制整数常量的类型是 int
, long int $ c $的第一个c>或
long long int
,其值将适合其中。同样,八进制或十六进制文字的类型为 int
, unsigned int
, long int
, unsigned long int
, long long int
或 unsigned long long int
。有关详细信息,请参见 N1570 6.4.4.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
和 -2
是常量表达式。一元-
运算符的结果与操作数具有相同的类型(即使该结果导致溢出,如 -INT_MIN $ c $
-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;
常量 1
和表达式 -1
均为 int
类型。该值存储在 int
对象 i
中;无需转换。 (严格来说,它是从 int
转换为 int
的,但这没关系。)
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
类型为 int
。它从 int
转换为 unsigned int
。
2
is of type int
. It's converted from int
to unsigned int
.
unsigned int k = -2;
-2
类型为 int
。它从 int
转换为 unsigned int
。这次,由于 -2
不在 unsigned int
的范围之外,因此转换是不平凡的;结果是 UINT_MAX-1
。
-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
.
某些术语:
常量被其他一些语言称为文字。它是代表恒定值的单个令牌。例如 1
和 0xff
。
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 是在编译时需要评估的表达式。常数是常数表达式;其操作数是常量或常量表达式的表达式也是如此。例如 -1
和 2 + 2
。
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屋!