Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of a 'switch 0' statement in C?

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?

like image 335
Jet Blue Avatar asked Dec 04 '17 00:12

Jet Blue


People also ask

What is the purpose of switch statement in C?

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.

What does case 0 switch mean?

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.

Is there case 0 in switch?

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.


1 Answers

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.

like image 112
Matteo Italia Avatar answered Nov 05 '22 23:11

Matteo Italia