What does this tidbit DO?
I run into the following inside a C codebase.
That caused some head scratching, until I realized that this is probably just a funny way to write a static assert.
Basically, sizeof() is a constant time value that is being evaluated by the compiler, I assume that the cast to void is to make this clear to the compiler that we are throwing away the value intentionally and that it shouldn’t actually generate any code here.
The rest is pretty basic, the compiler need to compute the size of the array, and to do that, it need to compute the value, but if the above statement is false, the value is –1, and that is not a valid size for the array, so a compiler error will be raised.
I think that there are better ways to do it, but I’m guessing this a more portable version?
Comments
Stunning hack!
Just found some links with more info: http://stackoverflow.com/questions/4079243/how-can-i-use-sizeof-in-a-preprocessor-macro http://www.pixelbeat.org/programming/gcc/static_assert.html http://stackoverflow.com/questions/27800343/sizeof-operator-in-define-directives
This is available as a builtin in C11 (_Static_assert) but before that there's no better way to write this that I know of. However, sane codebases generatelly define a macro that expands to something like this - so that the ugliness is in the macro and the code just says STATIC_ASSERT(64U >= crypto_secretbox_ZEROBYTES);.
Comment preview