I want to know , case 1 is not executed, but still line 6 works ..... so how exactly and when exactly is the variable declared and allocated memory and if its done on line 4 , how is it actually done , since case 1 is not even executed
If you try the following code snippet, you'll get a compiler errorBut if you add curly braces to the first case block, the code will compile successfullyBut if you add them to the second case block, you still get the "duplicate local variable" compiler errorIf you add curly braces to both, you're good to go and the code will compile successfullySo if the case block has curly braces, you've created a code block and variables declared within that block are only known (scoped) within that block. If the case block has no curly braces, the declared variables (like bool) are known (scoped) within the switch block. And there's probably a section in the JLS describing this behavior
Lilou Laure wrote:but how exactly and when exactly is the variable declared and allocated memory . when and how is it actually done , the flow i mean !
Honeslty I have no clue how your code snippet from the OP is handled behind the scenes, since it's actually quite meaningless no-op code
But adding another case to print the bool variable gives a good idea about what might happen behind the scenesAnd this is the compiler error: The local variable bool may not have been initialized. So the switch block is aware of the existence of variable bool but since it's a local variable it doesn't get any default value and the compiler knows that it might not be initialized if the switch expression evaluates to 3 and therefore gives you the compiler error.
And here's another oneAnd this is the compiler error: bool cannot be resolved to a variable. So once you have declared a varuable, you can use it. But in order to use it, you need to guarantee the compiler it is initialized and without using curly braces (otherwise you create a case code block and the variable becomes scoped to this block only).
If you really want some crazy meaningless code, you could do something like this...And yes, this code snippet compiles successfully