数字末尾带和不带“u”的宏常量

问题描述

用法有什么区别

#define CONSTANT_1 (256u)
#define CONSTANT_2 (0XFFFFu)

#define CONSTANT_1 (256)
#define CONSTANT_2 (0XFFFF)

我什么时候真的需要添加u?如果不添加,我们会遇到什么问题?

我对示例表达式更感兴趣,其中一种用法可能与其他用法出错。

解决方法

尾随的 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 用于 gcc 和 clang)。

256u 的类型为 unsigned int256 的类型为 int。另一个例子更微妙:0xFFFFu 的类型为 unsigned int,而 0xFFFF 的类型为 int,除了 int 只有 16 位类型的系统unsigned int

诸如 MISRA-C 之类的一些行业标准要求这种不断输入,在我看来,这是一种适得其反的建议。

,

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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...