Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable's scope in a switch case [duplicate]

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...

like image 318
Philippe Carriere Avatar asked Oct 08 '10 20:10

Philippe Carriere


People also ask

Is Double allowed in switch case?

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.

Are multiple values allowed in switch case?

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.

What happens when a variable runs out of scope?

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.

Can switch case have multiple conditions in C?

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.


1 Answers

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.

like image 76
Richard Cook Avatar answered Oct 01 '22 07:10

Richard Cook