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:03

>>2 I read the blog post and the comments. While it did confirm that I can't use const variables in static assertions (for no apparent reason, other than "because the standard says so"), I didn't see anything related to my greater problem of how to make _Static_assert into an expression (so that it isn't completely useless for macros).

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