In C11 it is legal to write, for instance:
int b = (some_function_returning_void(), 1020);
And you'll get back 1020. But it won't let you write:
int b = (_Static_assert(2 > 1, "all is lost"), 304);
gcc returning
error: expected expression before '_Static_assert'
And it would be inconvenient to use _Static_assert
outside of an expression sometimes since you're out of luck with preprocessor macros-based pseudo-functions that verify their arguments then.
_Static_assert
is, unfortunately, a special kind of declaration, not a function or an operator. You won't be able to slip it into an expression, unless you use something non-standard. E.g. compiler extensions like GCC's "statement expressions"
int b = ({ _Static_assert(2 > 1, "all is lost"); 304; });
or
int b = (({ _Static_assert(2 > 1, "all is lost"); }), 304);
This is doable in ISO C11. The trick is to put _Static_assert
in a struct declaration, in a sizeof expression:
sizeof(struct { _Static_assert(0, "yay it failed"); int dummy; })
The dummy field is necessary because empty struct is a GNU extension
, according to clang -std=c11 -Weverything
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With