Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to slip a _Static_assert into an expression in ISO C11?

Tags:

c

c11

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.

like image 408
L29Ah Avatar asked Jul 17 '18 18:07

L29Ah


2 Answers

_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);
like image 199
AnT Avatar answered Nov 19 '22 19:11

AnT


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.

like image 5
dpercy Avatar answered Nov 19 '22 20:11

dpercy