gpt4 book ai didi

c - C 的三元条件运算符是否创建新范围?

转载 作者:太空狗 更新时间:2023-10-29 15:25:55 24 4
gpt4 key购买 nike

标题基本上说明了一切,但我特别想知道下面的(稍微滥用的)宏是否应该工作(使用 C99 或更高版本),也就是说,它会返回一个指向有效部分的指针根据表达式的大小分配的堆栈内存:

#include <stdint.h>

#define NASTY(expr) ( \
8 == sizeof(expr) ? (void *)(&(uint64_t){(expr)}) : \
( \
4 == sizeof(expr) ? (void *)(&(uint32_t){(expr)}) : \
( \
2 == sizeof(expr) ? (void *)(&(uint16_t){(expr)}) : (void *)(&(uint8_t){(expr)}) \
) \
) \
)

编辑:

我对这样的宏感兴趣的原因是(1)我是一个 Nerd (2)我正在为需要动态memcpy结果的嵌入式应用程序编写一些代码生成宏表达式(例如 x*y+z)。我们正在处理一个能量敏感的应用程序,其中函数调用很重要。

最佳答案

我不知道你所说的“新作用域”是什么意思——在 C 语言中,“作用域”只与标识符相关,与对象生命周期无关。根据 6.5.2.5 复合文字,

If the compound literal occurs outside the body of a function, the object has static storage duration; otherwise, it has automatic storage duration associated with the enclosing block.

因此,如果您在函数体内使用此宏,则指向对象的生命周期将持续到封闭 block 的执行结束。这可能会或可能不会满足您的需求;你可能会因为这样写而惹上麻烦:

if (foo) {
p = NASTY(bar);
}
/* ... */
/* Do something with p */

关于c - C 的三元条件运算符是否创建新范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38795568/

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