Is there a useful case using a switch statement without braces?

If you use control structures in macros a switch instead of if comes handy since it has no dangling else problem.

#define DEBUG_PRINT(...) switch (!debug_mode) case 0: fprintf(__VA_ARGS__)

With that you don’t have surprises if a user of that macro puts this in an additional condition

if (unclear) DEBUG_PRINT(stderr, "This is really %unclear\n", unclear);
else {
 // do something reasonable here
}

Such a debug macro has the advantage of being always compiled (and then eventually optimized out). So the debug code has to remain valid through all the live time of the program.

Also observe here that it is important that the switch doesn’t use {}, otherwise the if/else example wouldn’t work either. All this could be achieved by other means (if/else , (void)0 and do/while tricks) but this one is the most convenient I know of.

And don’t take me wrong, I don’t say that everybody should use control structures inside macros, you certainly should know what you are doing. But there are situations where it is justified.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)