使用宏来为整数常量初始化对象 [英] Initializing objects with macros for integer constants

查看:109
本文介绍了使用宏来为整数常量初始化对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

http://www.open-std .org / jtc1 / sc22 / wg14 / www / docs / n1570.pdf
7.20.4引入宏整数常量


1以下类似函数的宏扩展为整数常量
适合初始化具有整数类型的对象
对应于< stdint.h>中定义的类型。每个宏名称
对应于7.20.1.2或7.20.1.5中的类似类型名称。

1 The following function-like macros expand to integer constants suitable for initializing objects that have integer types corresponding to types defined in <stdint.h>. Each macro name corresponds to a similar type name in 7.20.1.2 or 7.20.1.5.

我不太喜欢明白这一段。
宏基本上将相应的后缀打到未填充的数字上,如下所示:

I don't quite understand this paragraph. The macros basically slap the appropriate suffix onto an unsuffixed number as in:

UINT64_C(0x123) => 0x123ULL

但如果我想初始化uint64_t,我会这么做:

But if I wanted to initializes an uint64_t, I would just do:

uint64_t x = 0x123; 

我根本不打扰后缀。

为什么我在初始化时需要这些宏?

Why would I need these macros in initializations?

推荐答案

这个 UINT64_C(0x123 )宏创建一个立即无符号长long数,因此可以在变量参数函数中用于实例或中间计算,而无需转换为 uint64_t type,其中使用此特定数据类型非常重要。

this UINT64_C(0x123) macro creates an immediate unsigned long long number so it can be used in variable argument functions for instance or intermediate computations without the need for casting into the uint64_t type, where it is important that this particular data type is used.

示例:

printf("%llu\n",UINT64_C(0x123));

是正确的

printf("%llu\n",0x123);

不正确且为UB,因为数据大小不正确, printf 无法知道。

is incorrect and is UB because data size isn't correct, and printf cannot know that.

当你执行 uint64_t x = 0x123; 时,有一个赋值和隐式强制转换,所以不需要这样做(和 printf(%llu \ n,x); 是正确的)

when you do uint64_t x = 0x123;, there's an assignment and an implicit cast, so no need to do this (and printf("%llu\n",x); is correct)

另一种用法是在中间计算中,如下图所示:

Another usage is in intermediate computations, as illustrated below:

uint32_t a = 0xFFFFFFFF;
uint64_t x = a + UINT64_C(0xFFFFFFFF);

不会溢出而

x = a + 0xFFFFFFFF;

会溢出,因为中间结果存储在 uint32_t

will overflow because intermediate result is stored in a uint32_t

总之, UINT64_C(SOME_CONSTANT)之间的主要功能差异(uint64_t)SOME_CONSTANT 如果值溢出,你会在第一种情况下得到警告,在另一种情况下会得到转换(可能是警告,但这取决于编译器)。

As a conclusion, the main functional difference between UINT64_C(SOME_CONSTANT) and (uint64_t)SOME_CONSTANT is that if the value overflows, you'll get a warning in the first case for sure, and a "conversion" in the other case (and maybe a warning but that depends on the compiler).

这篇关于使用宏来为整数常量初始化对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆