My tutorial said this:
If "case" executes the statements below it until something like break; stops it, why does case 2 work? if case 2 was executed instead of case 1, then int y; would have never been executed/declared, and therefore it should cause a compile error, right?Note that although variable y was defined in case 1, it was used in case 2 as well. All cases are considered part of the same scope, so a declaration in one case can be used in subsequent cases.Code:switch (x) { case 1: int y;// okay, declaration is allowed y=4;// okay, this is an assignment break; case 2: y=5;// okay, y was declared above, so we can use it here too break; case 3: int z=4;// illegal, you can't initialize new variables in the case statements break; default: std::cout<<"default case"<<std::endl; break; }
Last edited by Nyap,