在case语句中使用

在case语句中使用

本文介绍了在case语句中使用{}。为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

案例 {} c $ c>语句?通常,无论 case 语句中有多少行,所有行都被执行。这是只是一个关于旧的/较新的编译器的规则,还是有背后的事情?

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;
  }
}

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


推荐答案

请考虑以下非常有用的示例:

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;
}

你会得到一个编译错误,因为 x 已在范围中定义。

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

将这些分隔到自己的子范围将不再需要声明 x 在switch语句之外。

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;
    }
}

这篇关于在case语句中使用{}。为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 12:44