Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are variables not local in case statements?

Tags:

java

I recently add another menu item to an android java app and was suprised that Eclipse said that variable from the previous case:break were not local (So I've just added a suffix to get by).

I'm a bit confused as in my mind, the 1st set of case:break would not be executed at all if the 2nd option was chosen. Could someone explain my faulty thinking please?

        case R.id.menuDebugMode:
            debugMode = !debugMode;
            if (debugMode){
                Toast.makeText(mainActivity.this, "Debug Mode on - NOT TO BE USED WHILST DRIVING", Toast.LENGTH_LONG).show();           
            } else {
                tvDebug.setText("");
                tvInfo.setText("");
            }
            SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
            SharedPreferences.Editor editor = settings.edit();
            editor.putBoolean("debugMode", debugMode);
            editor.commit();
        break;

        case R.id.menuSpeedMode:
            speedSignMode = !speedSignMode;
            if (speedSignMode){
                Toast.makeText(mainActivity.this, "SpeedSign Mode in use", Toast.LENGTH_LONG).show();           

            } else {
                    Toast.makeText(mainActivity.this, "MapSpeed Mode in use", Toast.LENGTH_LONG).show();            
            }
            SharedPreferences settings2 = getSharedPreferences(PREFS_NAME, 0);
            SharedPreferences.Editor editor2 = settings2.edit();
            editor2.putBoolean("speedSignMode", speedSignMode);
            editor2.commit();
        break;`
like image 575
SimpleSi Avatar asked Nov 05 '10 07:11

SimpleSi


2 Answers

You're right that at most one will execute, but a case does not create a new scope. You can manually create a block with its own scope.

case foo:
    {
       int var = ...
    }
    break;

case bar:
    {
       int var = ...
    }
    break;
like image 98
Matthew Flaschen Avatar answered Oct 20 '22 01:10

Matthew Flaschen


As in C, in Java a switch statement is not what one would expect when looking at it. The indendation makes it difficult to understand that a scope is not created. This all boils down to C, where a switch is just syntactic sugar. The compiler transforms a switch into a number of conditional jumps. This enables the language to use fall-through, a feature that during the design of C was intended ("break" remained optional). This Java feature remained compatible to C.

switch(a):
    case 1:
        dosomething();
    case 2:
        dosomemore();

gets translated into

if(a==1) jump ##1;
if(a==2) jump ##2;
jump ##3;
##1:
dosometing();
##2:
dosomemore();
##3:
like image 36
0xCAFEBABE Avatar answered Oct 20 '22 01:10

0xCAFEBABE