tags:
- Cpp
Integer Literal & Float Literal in C++
Do this at first: Type Deduce - Auto in C++
在使用 auto
关键字时,我们发现 auto
往往会将整数字面量推导成 int
类型。如下,我们给 a
赋值 0
远远小于 int
能够表示的最大值。既然 short
类型也能表示 0
,甚至 char
类型也可以。那为什么 auto
不将这个表达式中的 a
推导成 short
类型,甚至 char
类型?
auto a = 0; // a is deduced as int type, why not short or char?
这是因为在 C++ 中,整数字面量(例如 0
)的默认类型是 int
。编译器会优先选择最适合的类型来表示这个字面量,因此在这种情况下,auto
会推导出 int
类型,而不是其他的类型。
在 C++ 中,整数字面量可以是十进制的、八进制的、十六进制的和二进制的(C++14)。通过加入不同的前缀,我们就可以改变整数的基数。如下:
int decimal = 16;
int octal = 020; // 16 on decimal
int hexdecimal = 0x10; // or 0X10
int binary = 0b10000;
当整数字面量不带任何后缀时,一般默认的类型就是 int
类型。C++ 整型字面量一共有这几种不同的后缀(基数为10):
u
或 U
:表示 unsigned int
(默认)l
或 L
:表示 long int
(默认)ul
/ UL
等 :表示 unsigned long int
(默认)ll
或 LL
:long long int
ull
或 ULL
等:表示 unsigned long long int
z
或 Z
:表示 std::size
类型(C++23)uz
或 UZ
:同上。auto a = 0; // a is deduced as type int
auto b = 0u; // b is deduced as type unsigned int
auto c = 0l; // c is deduced as type long
auto d = 0ul; // d is deduced as type unsigned long
auto e = 0ll; // e is deduced as type long long
auto f = 0ull; // f is deduced as type unsigned long long
当字面量很长时,你可以用单引号作为分隔符在任意位置将字面量分隔开。在确定字面量时会忽略这些单引号。
同样的,浮点字面量也可以通过后缀来决定字面量的类型。当没有后缀时,默认定义为 double
类型。对于浮点数字面量,C++ 有以下的后缀:
f
或 F
:表示 float
l
或 L
:表示 long double
f16
、f32
、f64
、f128
、bf16
、F16
、F32
、F64
、F128
、BF16
的后缀。auto a = 0.0; // a is deduced as type double
auto b = 0.0f; // b is deduced as type float
auto c = 0.0l; // c is deduced as type long double