c - Is this a switch statement smell? -
i looking through someone's c code, , discovered didn't know possible. inside of cases, switch variable modified, intention another case executed after break.
switch (variable) { case 1: some_code(); variable = 3; break; case 2: more_code(); variable = 5; break; case 3: more_code(); variable = 5; break; case 4: my_code(); break; case 5: final_code(); break; }
the code seems working author intended. lucky, or guaranteed behaviour in c? assumed break statement cause execution jump directly after switch statement. wouldn't have expected continue testing every other case.
this common technique state machine type code. doesn't jump automatically imagine. switch
statement has put inside while
loop. in case, imagine loop like:
while (!done) { done = (variable == 5); switch (variable) { /*...*/ } }
alternatively, switch
statement inside function body, , function called loop until done condition met.
Comments
Post a Comment