[英]Does C's ternary conditional operator create a new scope?
The title basically says it all, but I am specifically interested to know if the following (slightly abusive) macro should be expected to work (with C99 or greater), that is, that it will return a pointer to a valid section of stack allocated memory based on the size of the expression: 标题基本上都说明了一切,但我特别感兴趣的是知道是否应该使用以下(略微滥用)宏(使用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)}) \
) \
) \
)
EDIT: 编辑:
The reason I am interested in such a macro is (1) I am aa nerd and (2) I am writing some code-generating macros for an embedded application that need to dynamically memcpy
the result of an expression (such as x*y+z
). 我对这样一个宏感兴趣的原因是(1)我是一个书呆子和(2)我正在为一个需要动态
memcpy
表达式结果的嵌入式应用程序编写一些代码生成宏(例如x*y+z
)。 We are working in an energy sensitive application where function calls matter. 我们正在一个能量敏感的应用程序中,函数调用很重要。
I don't know what you mean by "a new scope" - in C, "scope" is relevant only to identifiers, not object lifetime. 我不知道“新范围”是什么意思 - 在C中,“范围”仅与标识符有关,而与对象生命周期无关。 Per 6.5.2.5 Compound literals,
每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.
否则,它具有与封闭块相关的自动存储持续时间。
Thus, if you use this macro inside a function body, the lifetime of the pointed-to object will persist until execution of the enclosing block ends. 因此,如果在函数体内使用此宏,则指向对象的生命周期将持续,直到封闭块的执行结束。 This might or might not meet your needs;
这可能会也可能不会满足您的需求; you could get in trouble by writing:
你写错了可能会遇到麻烦:
if (foo) {
p = NASTY(bar);
}
/* ... */
/* Do something with p */
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.