c ++:为什么我们可以在切换的情况下声明一个变量 [英] c++: why can we declare a variable in case of switch

查看:123
本文介绍了c ++:为什么我们可以在切换的情况下声明一个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  int i; 
i = 2;
switch(i)
{
case 1:
int k;
break;
case 2:
k = 1;
cout<< k<< endl;
break;
}

我不知道为什么上面的代码工作。 p>

这里,我们不能进入case 1,但为什么我们可以在case 2中使用 k

解决方案

实际上有两个问题:



1。为什么我可以在 case 标签后声明一个变量?



这是因为在C ++标签中in form:



N3337 6.1 / 1


p>

...




  • attribute-specifier-seqopt case constant-expression 语句



...


c> C ++ 也被视为语句(而不是 C ) :



N3337 6/1:


>:



...




  • em>



...


2。为什么我可以跳过变量声明,然后使用它?



因为:
N3337 6.7 / 3


可以传入但不是以初始化绕过声明的方式。 A
程序跳转
转换切换语句的条件到案例标签在这方面被视为跳转。)



从具有自动存储持续时间的变量不在范围内的点到其范围内有问题的点 除非变量具有标量类型,类类型具有一个简单的默认
构造函数和一个简单析构函数,这些类型之一的cv限定版本,或者一个
之前的数组


由于 k 是的标量类型,并且不会在声明点初始化时跳过它的声明。这在语义上是等价的:

  goto label; 

int x;

label:
cout<< x < endl;

但是,如果 x 在声明时初始化:

  goto label; 

int x = 58; //错误,跳过初始化的声明

label:
cout<< x < endl;


int i;
i = 2;
switch(i)
{
    case 1: 
        int k;
        break;
    case 2:
        k = 1;
        cout<<k<<endl;
        break;
}

I don't know why the code above works.

Here, we can never go into case 1 but why we can use k in case 2?

解决方案

There are actually 2 questions:

1. Why can I declare a variable after case label?

It's because in C++ label has to be in form:

N3337 6.1/1

labeled-statement:

...

  • attribute-specifier-seqopt case constant-expression : statement

...

And in C++ declaration statement is also considered as statement (as opposed to C):

N3337 6/1:

statement:

...

  • declaration-statement

...

2. Why can I jump over variable declaration and then use it?

Because: N3337 6.7/3

It is possible to transfer into a block, but not in a way that bypasses declarations with initialization. A program that jumps (The transfer from the condition of a switch statement to a case label is considered a jump in this respect.)

from a point where a variable with automatic storage duration is not in scope to a point where it is in scope is ill-formed unless the variable has scalar type, class type with a trivial default constructor and a trivial destructor, a cv-qualified version of one of these types, or an array of one of the preceding types and is declared without an initializer (8.5).

Since k is of scalar type, and is not initialized at point of declaration jumping over it's declaration is possible. This is semantically equivalent:

goto label;

int x;

label:
cout << x << endl;

However this wouldn't work if x was initialized at point of declaration:

 goto label;

    int x = 58; //error, jumping over declaration with initialization

    label:
    cout << x << endl;

这篇关于c ++:为什么我们可以在切换的情况下声明一个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆