6

I came across the following line of code, and I can't figure out what it does.

#define static_assert(a, b) do { switch (0) case 0: case (a): ; } while (0)

What does the switch (0) part do? Assuming 0 is equivalent to false, does that mean we never enter the switch statement?

Also for the line case (a), how can you give the unknown a variable as a case?

Jet Blue
  • 5,109
  • 7
  • 36
  • 48
  • 3
    All this seems to be doing is checking that `a` is a compile-time constant. `b` isn't even used. The code it expands to just falls through without really doing anything. `switch (0)` is no different from `switch (100)` or any other value. It branches to `case 0` and execution continues from there. And `a` shouldn't be a variable, it's whatever you pass to the macro. It should be a constant. It you pass a variable, you will get a compile-time error. – Tom Karzes Dec 04 '17 at 00:47
  • 3
    [`static_assert`](https://stackoverflow.com/q/1647895/995714) can give you some hint although the intention and usage here is different and that name is not a good choice – phuclv Dec 04 '17 at 00:50
  • 3
    Defective as an implementation of the standard `static_assert` as it won't work outside of a function – M.M Dec 04 '17 at 01:39

1 Answers1

8

switch(0) will always execute the block of code associated with the case 0: block; still, here there's no actually executed code - both cases are empty.

The point here is to make the compiler angry at compile time if the asserted expression (a) is not verified: in this case, the expanded macro will have two case 0: - the one provided explicitly, and the one that uses the result of the asserted expression (so, 0 in case it failed); this results in a switch with two identical case, which is not allowed and makes the compiler stop with an error at compile time.

This will also fail if the passed expression is not a constant evaluated at compile time (as you cannot have runtime-determined case values), which is also expected from a static_assert.

Matteo Italia
  • 123,740
  • 17
  • 206
  • 299