gpt4 book ai didi

c - stdint.h 中的 {U,}INTn_C 宏有什么意义?

转载 作者:行者123 更新时间:2023-12-01 12:09:27 25 4
gpt4 key购买 nike

什么时候真正需要这些宏?

我的系统 (gcc/glibc/linux/x86_64) stdint.h使用( __ -prefixed)这些变体来定义:

# define INT64_MIN      (-__INT64_C(9223372036854775807)-1)
# define INT64_MAX (__INT64_C(9223372036854775807))
# define UINT64_MAX (__UINT64_C(18446744073709551615))
# define INT_LEAST64_MIN (-__INT64_C(9223372036854775807)-1)
# define INT_LEAST64_MAX (__INT64_C(9223372036854775807))
# define UINT_LEAST64_MAX (__UINT64_C(18446744073709551615))
# define INT_FAST64_MIN (-__INT64_C(9223372036854775807)-1)
# define INT_FAST64_MAX (__INT64_C(9223372036854775807))
# define UINT_FAST64_MAX (__UINT64_C(18446744073709551615))
# define INTMAX_MIN (-__INT64_C(9223372036854775807)-1)
# define INTMAX_MAX (__INT64_C(9223372036854775807))
# define UINTMAX_MAX (__UINT64_C(18446744073709551615))

然而对于 limits.h它似乎与:
#   define LONG_MAX 9223372036854775807L
# define ULONG_MAX 18446744073709551615UL

为什么不能 stdint.h忘记 _C宏,只需执行以下操作:
#   define INT_LEAST64_MAX  9223372036854775807 //let it grow as needed
# define UINT_LEAST64_MAX 18446744073709551615U //just the U

这些宏的用例是什么?

我能想到的唯一一个是我想要一个足够宽的常量可用于 cpp 条件,同时我不希望它太宽:
//C guarantees longs are at least 32 bits wide
#define THREE_GIGS_BUT_MAYBE_TOO_WIDE (1L<<30)
#define THREE_GIGS (INT32_C(1)<<30) //possibly narrower than the define above

最佳答案

What is the point of the {U,}INTn_C macros in <stdint.h>?



它们确保常量的最小类型宽度和符号。

它们“扩展为对应于类型 (u)int_leastN_t. 的整数常量表达式”
123 << 50                // likely int overflow (UB)
INT32_C(123) << 50 // likely int overflow (UB)
INT64_C(123) << 50 // well defined.
INT32_C(123)*2000000000 // likely int overflow (UB)
UINT32_C(123)*2000000000 // well defined - even though it may mathematically overflow

定义 computed constants 时很有用.
// well defined, but the wrong product when unsigned is 32-bit
#define TBYTE (1024u*1024*1024*1024)

// well defined, and specified to be 1099511627776u
#define TBYTE (UINT64_C(1024)*1024*1024*1024)

它还通过 _Generic 影响代码.下面可以将代码引导到 unsigned long , unsignedunsigned long long .
(unsigned long) 123
UINT32_C(123)
UINT64_C(123)

关于c - stdint.h 中的 {U,}INTn_C 宏有什么意义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53243019/

25 4 0