数字末尾带和不带 "u" 的宏常量
macro constants with and without "u" at the end of a number
用法有什么区别
#define CONSTANT_1 (256u)
#define CONSTANT_2 (0XFFFFu)
和
#define CONSTANT_1 (256)
#define CONSTANT_2 (0XFFFF)
我什么时候真正需要添加 u
?如果不添加,我们会遇到什么问题?
我对示例表达式更感兴趣,其中一种用法可能会与另一种用法出错。
u
表示十进制常量为unsigned
.
否则,由于该值在有符号整数范围内,因此将被视为有符号整数。
引用 C11
,第 6.4.4.1 章,整数常量
The type of an integer constant is the first of the corresponding list in which
its value can be represented.
Suffix Decimal Constant Octal or Hexadecimal Constant
---------------------------------------------------------------------------
none int int
long int unsigned int
long long int long int
unsigned long int
long long int
unsigned long long int
u or U unsigned int unsigned int
unsigned long int unsigned long int
unsigned long long int unsigned long long int
结尾的u
使常量具有无符号类型。对于给出的示例,这可能是不必要的,并且可能会产生令人惊讶的后果:
#include <stdio.h>
#define CONSTANT_1 (256u)
int main() {
if (CONSTANT_1 > -1) {
printf("expected this\n");
} else {
printf("but got this instead!\n");
}
return 0;
}
这个令人惊讶的结果的原因是比较是使用无符号算术执行的,-1
被隐式转换为 unsigned int
,值为 UINT_MAX
。启用额外警告将节省现代编译器的时间(-Wall -Werror
for gcc and clang)。
256u
的类型为 unsigned int
,而 256
的类型为 int
。另一个例子更微妙:0xFFFFu
的类型为 unsigned int
,而 0xFFFF
的类型为 int
,但在 int
只有 16 位类型的系统上除外unsigned int
.
一些行业标准(例如 MISRA-C)要求进行这种不断的输入,在我看来这是适得其反的建议。
用法有什么区别
#define CONSTANT_1 (256u)
#define CONSTANT_2 (0XFFFFu)
和
#define CONSTANT_1 (256)
#define CONSTANT_2 (0XFFFF)
我什么时候真正需要添加 u
?如果不添加,我们会遇到什么问题?
我对示例表达式更感兴趣,其中一种用法可能会与另一种用法出错。
u
表示十进制常量为unsigned
.
否则,由于该值在有符号整数范围内,因此将被视为有符号整数。
引用 C11
,第 6.4.4.1 章,整数常量
The type of an integer constant is the first of the corresponding list in which its value can be represented. Suffix Decimal Constant Octal or Hexadecimal Constant --------------------------------------------------------------------------- none int int long int unsigned int long long int long int unsigned long int long long int unsigned long long int u or U unsigned int unsigned int unsigned long int unsigned long int unsigned long long int unsigned long long int
结尾的u
使常量具有无符号类型。对于给出的示例,这可能是不必要的,并且可能会产生令人惊讶的后果:
#include <stdio.h>
#define CONSTANT_1 (256u)
int main() {
if (CONSTANT_1 > -1) {
printf("expected this\n");
} else {
printf("but got this instead!\n");
}
return 0;
}
这个令人惊讶的结果的原因是比较是使用无符号算术执行的,-1
被隐式转换为 unsigned int
,值为 UINT_MAX
。启用额外警告将节省现代编译器的时间(-Wall -Werror
for gcc and clang)。
256u
的类型为 unsigned int
,而 256
的类型为 int
。另一个例子更微妙:0xFFFFu
的类型为 unsigned int
,而 0xFFFF
的类型为 int
,但在 int
只有 16 位类型的系统上除外unsigned int
.
一些行业标准(例如 MISRA-C)要求进行这种不断的输入,在我看来这是适得其反的建议。