何时真正需要这些宏?
我的系统(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
最佳答案
它们确保最小的字体宽度和符号常数。
它们“扩展为与(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
,unsigned
和unsigned long long
。(unsigned long) 123
UINT32_C(123)
UINT64_C(123)
关于c - stdint.h中的{U,} INTn_C宏有什么意义?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53243019/