• Error C2361: initialization of (identifier) is skipped by (default) label


    看下面一段代码:

    // C2361.cpp
    void func( void ) {
    int x;
    switch (x) {
    case 0 :
    int i = 1;
    { int j = 1; }
    default : // C2361 error
    int k = 1;
    }
    }

    编译时会报错,Error C2361: initialization of (identifier) is skipped by (default) label,msdn解释是这样的,

    The initialization of identifier can be skipped in a switch statement. You cannot jump past a declaration with an initializer unless the declaration is enclosed in a block. (Unless it is declared within a block, the variable is within scope until the end of the switch statement.)

    在 switch 语句中可以跳过 identifier 的初始化。 不能跳过带有初始值设定项的声明,除非该声明包括在块中。 (直到 switch 语句结尾变量始终在范围内,除非该变量在块中声明。

    解决办法:加上括号

    // C2361b.cpp
    // compile with: /c
    void func( void ) {
    int x = 0;
    switch (x) {
    case 0 :
    { int j = 1; int i = 1;}
    default :
    int k = 1;
    }
    }


    下面是网友的文章:

    在C++中,switch-case中的case实质上只是一个标签(label),就像goto的标签一样。case中的代码并没有构成一个局部作用域,虽然它的缩进给人一种错觉,好像它是一个作用域。也就是说,所有在case里面定义的变量作用域都是switch{...},在后面其他case中依然可以访问到这个变量。而switch本质上相当于goto,因此下面紧跟switch的打印语句永远不会执行到

    switch(selector)  
    {
    cout << selector;
    case selector_a:
    int i = 1;
    case selector_b:
    // i在此仍然可见
    }

    具体参考:http://blog.csdn.net/outmanlee/article/details/6714560

  • 相关阅读:
    手机操作
    模拟手机操作
    get_attribute_value
    test_order
    信息收集-FOFA资产收集与FOFA api
    html中form讲解
    安装redis
    yum vs rpm
    yum 安装java环境
    显示当前目录所有文件大小的命令ls -lht
  • 原文地址:https://www.cnblogs.com/youxin/p/2431024.html
Copyright © 2020-2023  润新知