Switch case weird scoping

前端 未结 2 1130
我寻月下人不归
我寻月下人不归 2020-12-02 21:27

Reviewing some 3rd party C code I came across something like:

switch (state) {
case 0: 
    if (c==\'A\') { // open brace
        // code...
    break; // br         


        
2条回答
  •  甜味超标
    2020-12-02 22:01

    In C and C++ it is legal to jump into loops and if blocks so long as you don't jump over any variable declarations. You can check this answer for an example using goto, but I don't see why the same ideas wouldn't apply to switch blocks.

    The semantics are different than if the } was above case 1 as you would expect.
    This code actually says if state == 0 and c != 'A' then go to case 2 since that's where the closing brace of the if statement is. It then processes that code and hits the break statement at the end of the case 2 code.

提交回复
热议问题