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?
A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each switch case.
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.
using Switch is like == in "if statement" and not === (doesn't check for type). Only empty string or NULL would result in an Integer 0 - other than that, they are considered string 0.
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.
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