I think I don't understand how the scope works in a switch case.
Can someone explain to me why the first code doesn't compile but the second does ?
Code 1 :
int key = 2; switch (key) { case 1: String str = "1"; return str; case 2: String str = "2"; // duplicate declaration of "str" according to Eclipse. return str; }
Code 2 :
int key = 2; if (key == 1) { String str = "1"; return str; } else if (key == 2) { String str = "2"; return str; }
How come the scope of the variable "str" is not contained within Case 1 ?
If I skip the declaration of case 1 the variable "str" is never declared...
Usually switch-case structure is used when executing some operations based on a state variable. There an int has more than enough options. Boolean has only two so a normal if is usually good enough. Doubles and floats aren't really that accurate to be used in this fashion.
You can use N number of case values for a switch expression. The Case unit must be unique, otherwise, a compile-time error occurred. The default case is optional.
Nothing physical happens. A typical implementation will allocate enough space in the program stack to store all variables at the deepest level of block nesting in the current function. This space is typically allocated in the stack in one shot at the function startup and released back at the function exit.
A switch statement—or simply a case statement—is a control flow mechanism that determines the execution of a program based on the value of a variable or an expression. Using a switch statement allows you to test multiple conditions and only execute a specific block if the condition is true.
I'll repeat what others have said: the scope of the variables in each case
clause corresponds to the whole switch
statement. You can, however, create further nested scopes with braces as follows:
int key = 2; switch (key) { case 1: { String str = "1"; return str; } case 2: { String str = "2"; return str; } }
The resulting code will now compile successfully since the variable named str
in each case
clause is in its own scope.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With