简体   繁体   中英

static class members and switches

I got a little problem, I get an error:
"C2361: initialization of *identifier* is skipped by 'default' label"

I use an internal class member to set the chosen approach used in my methods.
The methods use this internal member ( static int ) with a switch to determine which approach was set.
The switch needs an intial value when compiling, so I decided to use a static const int . However, VS is still unhappy, and I can't change the static const int as well. I am pretty sure this ain't a big deal, but it's quite frustrating.

example:

class test{
    public:
    static int Val;
    static void setVal(int val);
    static int doStuff(void);
};

test::setVal(int val){
    Val=val;
}

test::doStuff(){
    switch(Val){
    case 1:
    // do stuff
    case 2:
    // do other stuff
    default:
    // do default
    }
}

Many thanks for any tips or solutions

There are numerous problems with he code you have posted. But assuming there are no other issues the following code will produce what you are experiencing:

test.h:

class test{
    public:
    static int Val;
    static void setVal(int val);
    static int doStuff(void);
};

test.cpp:

#include "test.h"

int test::Val = 0;

void
test::setVal(int val){
    Val=val;
}

int
test::doStuff(){
    switch(Val){
    case 1:
    // dostuff
        int apples = 1; /* problem line */
        break;
    default:
    // do default
        break;
    }
    return 0;
}

int main(int argc, char **argv)
{
    return 0;
}

Will produce the error:

error C2361: initialization of 'apples' is skipped by 'default' label

The reason for this is because you are trying to initialise a variable within the case statement. Visual Studio is complaining that there is no guarantee that the variable will be initialised because the case statement may be skipped over.

The question linked here gives the reason for this behavior.

But to put it briefly there is a chance that your code will jump to a case statement after the initialisation of your variable and visual studio does not allow such a case since it may lead to undefined behavior.

To quote the standard ( ISO C++ '03 - 6.7/3 ):

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM