交叉初始化的迹象是什么? [英] What are the signs of crosses initialization?

查看:254
本文介绍了交叉初始化的迹象是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码:

#include <iostream>
using namespace std;

int main()
{
    int x, y, i;
    cin >> x >> y >> i;
    switch(i) {
        case 1:
            // int r = x + y; -- OK
            int r = 1; // Failed to Compile
            cout << r;
            break;
        case 2:
            r = x - y;
            cout << r;
            break;
    };
}

G ++抱怨交叉初始化'int r' /code>.My questions are:

G++ complains crosses initialization of 'int r'.My questions are:


  1. 什么是交叉初始化

  2. 为什么第一个初始化程序 x + y 通过编译,但后来失败?

  3. 所谓交叉初始化的问题是什么?

  1. What is crosses initialization?
  2. Why do the first initializer x + y pass the compilation,but the later failed?
  3. What are the problems of so-called crosses initialization?

EDIT

我知道我应该使用括号来指定 r 的范围,但我想知道为什么为什么在多情况切换语句中不能定义非POD。

EDIT:
I know I should use brackets to specify the scope of r but I want to know why,for example why non-POD could not be defined in multi-case switch statement.

谢谢。

推荐答案

具有 int r = x + y; 的版本不会编译。

问题是 r 有可能在没有执行初始化程序的情况下到达范围。如果你完全删除了初始化器,代码将编译得很好(例如,这行会读取 int r; )。

The problem is that it is possible for r to come to scope without its initializer being executed. The code would compile fine if you removed the initializer completely (i.e. the line would read int r;).

你可以做的最好的事情是限制变量的范围。

The best thing you can do is to limit the scope of the variable. That way you'll satisfy both the compiler and the reader.

switch(i)
{
case 1:
    {
        int r = 1;
        cout << r;
    }
    break;
case 2:
    {
        int r = x - y;
        cout << r;
    }
    break;
};

标准说(6.7 / 3):

The Standard says (6.7/3):


有可能传入一个块,但不是以初始化绕过声明的方式。从自动存储持续时间不在范围内的局部变量到其范围内的点的点跳转的程序,除非变量具有POD类型(3.9)并且没有初始化程序(8.5)声明。

It is possible to transfer into a block, but not in a way that bypasses declarations with initialization. A program that jumps from a point where a local variable with automatic storage duration is not in scope to a point where it is in scope is ill-formed unless the variable has POD type (3.9) and is declared without an initializer (8.5).

这篇关于交叉初始化的迹象是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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