gpt4 book ai didi

c - stdint.h 中这个神秘的宏加号是什么?

转载 作者:太空狗 更新时间:2023-10-29 16:28:15 26 4
gpt4 key购买 nike

请看我的代码:

#include <stdint.h>

int main(int argc, char *argv[])
{
unsigned char s = 0xffU;
char ch = 0xff;
int val = 78;
((int8_t) + (78)); /*what does this mean*/

INT8_C(val); /*equivalent to above*/

signed char + 78; /*not allowed*/

return 0;
}

我发现 <stdint.h> 中的宏定义是:

#define INT8_C(val) ((int8_t) + (val))

这个加号是什么意思?

最佳答案

片段:

((int8_t) + (78));

是一个表达式,它取值78,应用一元+,然后将其转换为int8_t 类型,然后将其丢弃。它与法律表达没有什么不同:

42;
a + 1;

它还评估表达式然后丢弃结果(尽管如果编译器可以判断没有副作用,这些可能会被优化不存在)。

这些“裸”表达式在 C 中完全有效,通常只有在它们有副作用时才有用,例如 i++,它计算 i 并将其丢弃副作用是它增加了值(value)。

应该使用该宏的方式更多的是:

int8_t varname = INT8_C (somevalue);

看似多余的一元+运算符的原因可以在标准中找到。引用 C99 6.5.3.3 一元算术运算符/1:

The operand of the unary + or - operator shall have arithmetic type;

并且,在 6.2.5 Types,/18 中:

Integer and floating types are collectively called arithmetic types.

换句话说,一元 + 阻止您在宏中使用所有其他数据类型,例如指针、复数或结构。

最后,您的原因:

signed char + 78;

代码段不起作用是因为它不是一回事。这个开始声明类型为 signed char 的变量,但是当它到达 + 时就卡住了,因为那不是合法的变量名。要使其等同于您的工作代码段,您可以使用:

(signed char) + 78;

这是将值 +78 转换为类型 signed char

而且,根据 C99 7.8.14 Macros for integer constants/2,您还应该小心在这些宏中使用非常量,它们不能保证工作:

The argument in any instance of these macros shall be an unsuffixed integer constant (as defined in 6.4.4.1) with a value that does not exceed the limits for the corresponding type.

6.4.4.1 简单地指定了带有各种后缀(UULULLLLL 和对应的小写字母,具体取决于类型)。底线是它们必须是常量而不是变量。

例如,glibc 有:

# define INT8_C(c)      c
# define INT16_C(c) c
# define INT32_C(c) c
# if __WORDSIZE == 64
# define INT64_C(c) c ## L
# else
# define INT64_C(c) c ## LL
# endif

这将允许您的 INT8_C 宏正常工作,但文本 INT64_C(val) 将被预处理为 valLvalLL,这两个你都不想要。

关于c - stdint.h 中这个神秘的宏加号是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7642591/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com