Using {} in a case statement. Why?

mahmood picture mahmood · Nov 17, 2013 · Viewed 8.2k times · Source

What is the point with using { and } in a case statement? Normally, no matter how many lines are there in a case statement, all of the lines are executed. Is this just a rule regarding older/newer compilers or there is something behind that?

int a = 0;
switch (a) {
  case 0:{
    std::cout << "line1\n";
    std::cout << "line2\n";
    break;
  }
}

and

int a = 0;
switch (a) {
  case 0:
    std::cout << "line1\n";
    std::cout << "line2\n";
    break;
}

Answer

Rotem picture Rotem · Nov 17, 2013

The {} denotes a new block of scope.

Consider the following very contrived example:

switch (a)
{
    case 42:
        int x = GetSomeValue();
        return a * x;
    case 1337:
        int x = GetSomeOtherValue(); //ERROR
        return a * x;
}

You will get a compiler error because x is already defined in the scope.

Separating these to their own sub-scope will eliminate the need to declare x outside the switch statement.

switch (a)
{
    case 42: {
        int x = GetSomeValue();
        return a * x; 
    }
    case 1337: {
        int x = GetSomeOtherValue(); //OK
        return a * x; 
    }
}