HOME BLOG ARCHIVE TAGS

C/C++ switch statements are good maintenance helpers

March 15, 2017

C/C++ switch statements are interesting constructs, known to enable controversial and abused code. But they also allow compilers to aid in code maintenance. Let’s consider a small example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
// test.c
#include <stdio.h>

int main(int argc, char *argv[])
{
    enum {
        OPT1,
        OPT2
    } opt = OPT1;

    switch ( opt ) {
    case OPT1:
        printf("opt1!\n");
        break;
    }

    return 0;
}

If compiled with GCC -Wswitch (enabled by -Wall), a nice enumeration warning is reported:

1
2
3
4
test.c: In function ‘main’:
test.c:11:2: warning: enumeration value ‘OPT2’ not handled in switch [-Wswitch]
  switch ( opt ) {
  ^

For large code bases, this can be the difference between buggy and correct software (bringing a new perspective to “avoid having bool function parameters”).