gdoug gdoug - 10 months ago 47
C Question

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:

#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)}) \
) \
) \


The reason I am interested in such a macro is (1) I am a a nerd and (2) I am writing some code-generating macros for an embedded application that need to dynamically
the result of an expression (such as
). 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. Per Compound literals,

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 */