Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Turn assertion statement into expression in C

Name: Anonymous 2013-12-05 22:29

Does anyone know if there's a way to turn arbitrary statements into expressions in C?

I have a macro defined like this:
#define SAFE_WHATEVER(arg1) (_Static_assert(arg1 != bad_shit, "Bad shit!"), whatever(arg1))

Pretty straightforward, it wraps a function with a static check of the argument. In theory, due to the use of the comma operator, (do_shit(), do_more_shit()) should execute both functions, but the result of the expression should be whatever do_more_shit() returns.

Unfortunately, when I actually use this macro, I get this error from clang, in reference to my static assertion:
error: expected expression

So basically I need some kind of way to turn _Static_assert(whatever) into an expression so clang will stop bitching at me.

I'd just do
#define SAFE_WHATEVER(arg1) whatever(arg1); _Static_assert(arg1 != bad_shit, "Bad shit!");
which would let me write things like
int thing = SAFE_WHATEVER(10);
// expands to...
int thing = whatever(10);
_Static_assert(10 != bad_shit, "Bad shit!");

but then this causes obvious problems in all kinds of situations...
for (int i = 0; i < thing; i = SAFE_WHATEVER(i)) // nope!

Another weird thing:
#define HERP 42
_Static_assert(HERP == 42);

works just fine, but
const int derp 42;
_Static_assert(derp == 42);

gives:
error: static_assert expression is not an integral constant expression

It's like no one even tried to use this language construct before they implemented it.

Name: Anonymous 2013-12-05 23:21

>>3
as far as I know there is not a standard way
I would use the GCC lambda extension #define SAFE_WHATEVER(arg1) ({_Static_assert(arg1 != bad_shit, "Bad shit!"); whatever(arg1);})
1: I am not sure if this thing works
2: I think clang has something like that too

Name: 4 2013-12-05 23:24


Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List