Variable's Scope in a Switch Case

Variable's scope in a switch case

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.

Javascript scope variable to switch case?

Since var creates variables at function scope anyway, using it is pretty pointless. For this to work at a granularity below function scopes you'll have to use let and a browser/compiler which supports it, and then introduce a new block which you can scope things to (within switch it's simply invalid syntax):

if (true) {
let s;

switch (i) {
...
}
}

This scopes s to the if block, which for all intents and purposes is identical to the "switch scope" here.

If you cannot support let, you'll need to use an IIFE:

(function () {
var s;

switch (...) ...
})();

Java switch : variable declaration and scope

The scope is, just as usual, delimited by { and }.

How does java scope declarations in switch case statements?

Declarations aren't "run" - they're not something that needs to execute, they just tell the compiler the type of a variable. (An initializer would run, but that's fine - you're not trying to read from the variable before assigning a value to it.)

Scoping within switch statements is definitely odd, but basically the variable declared in the first case is still in scope in the second case.

From section 6.3 of the JLS:

The scope of a local variable declaration in a block (§14.4) is the rest of the block in which the declaration appears, starting with its own initializer and including any further declarators to the right in the local variable declaration statement.

Unless you create extra blocks, the whole switch statement is one block. If you want a new scope for each case, you can use braces:

case 1: {
int y = 7;
...
}
case 2: {
int y = 5;
...
}

What is the JavaScript variable scope in a switch / case statement?

Javascript does not use block scope.

Therefore, all local variables are in scope throughout the entire function in which they were declared.

However, in your particular case, there is no C-like language (that I know of) in which each case statement forms an independent scope.

For example, the following C# code will not compile:

switch(someVar) {
case 1:
int a;
break;
case 2:
int a; //'a' is already defined
break;
}

c++ Declaring a variable inside a switch statement

The reason why some variable declarations are not allowed in a switch statement is: it is illegal for switch-based control flow to jump over a variable initialisation.

In your case, I assume the type of commonData has trivial initialisation (no constructor and no non-trivial members), so declaring it is perfectly fine, as would be declaring just int someInt;. However, int someInt = 1; is not allowed, since the initialisation would be skipped whenever mode is not abc.

I can't quite see what you'd get from declaring commonData only once, except for saving some typing at the cost of obscuring the code ("where did commonData come from?" when reading a case block), which is never a good trade. So I would just use {} inside each case "block" and declare commonData in each one which needs it. Or declare commonData above the switch.

But if you really want the same commonData to be shared by all cases and yet local to the switch block, you can fine-tune the scopes. Something like this:

switch(mode)
{
SomeType commonData;
case abc:
{
...
commonData = manager->getDataByIndex(this->Data.particularData);
int someInt = 1;
...
break;
}
case xyz:
...
commonData = manager->getDataByIndex(this->Data.particularData);
break;
default:
...
break;
}

or this:

switch(mode)
{
case abc:
SomeType commonData;
...
commonData = manager->getDataByIndex(this->Data.particularData);
{
int someInt = 1;
...
break;
}
case xyz:
...
commonData = manager->getDataByIndex(this->Data.particularData);
break;
default:
...
break;
}

But please, think of the next maintainer, and don't play such tricks.


The answer above assumes struct commonData; is actually a "typo" in your code: literally, it would forward-declare a type, and not declare a variable. But that matches neither usage in the rest of your code, nor the text of your question, so I took the liberty of fixing this.

scope of a variable in java in switch

Because the block is what follows the switch statement, not each case within it:

switch (...) { // start of block
case: ...
break;
...
} // end of block

Writing break doesn't put an end to the block when it's used in a for loop; likewise, writing case doesn't begin a new block when it's used in a switch. It might help to think of them as labels to jump to within the block.

If you want to reuse the variable, you might define it within a block after your case:

case abc: {int i=0 ...}
break;

Variable declaration in a C# switch statement

I believe it has to do with the overall scope of the variable, it is a block level scope that is defined at the switch level.

Personally if you are setting a value to something inside a switch in your example for it to really be of any benefit, you would want to declare it outside the switch anyway.

odd variable scope in switch statement

Cases do not create scope in c++ or in c#. All of those variables declared inside a case are in the same scope, that of the switch statement. You need to use braces if you want those variables to be local to some specific case:

switch (personType)
{
case 1: {
Employee emp = new Employee();
emp.ExperienceInfo();
break;
}
case 2: {
Employee emp = new Employee();
// No longer an error; now 'emp' is local to this case.
emp.ManagementInfo();
break;
}
case 3: {
Student st = new Student();
st.EducationInfo();
break;
}
...
}


Related Topics



Leave a reply



Submit