Error: transfer of control bypasses initialization of: variable XXX solution

Error: transfer of control bypasses initialization of: variable XXX

The nature of the problem, causes and Solutions

The nature of the problem

The code may skip the initialization of some variables, which makes the program access the uninitialized variables and crash.

Causes

I encountered this problem when porting the code from the vs compiling environment of windows to the G + + of Linux (actually compiling CUDA C + + code with nvcc, but the nvcc background also calls G + + to compile C / C + + part of the code). Later, it was found that in vs environment, it was just a warning, but in G + +, it was an error, so this problem must be solved.

terms of settlement

    whether the variables in the analysis code are initialized, whether the variables are declared after the goto statement in the analysis code, and if so, move the variable declaration to the front of goto .
// error
goto SomeWhere;
int var = 10;
// right
int ver = 10;
goto SomeWhere;
    analyze whether or switch statements appear in the code, because switch statements are essentially implemented with goto , so the above problems may also exist. In addition to reference 2, write the variable declaration before switch, add curly brackets to each branch of switch , or change the switch statement to if / else .
// error
switch (choice)
{
    case 1:
        // do something
        break;
    case 2: 
        // do something
}
// right
switch (choice)
{
    case 1:
    {
        // do something
        break;
    }
    case 2: 
    {
        // do something
    }
}
// or
if(choice == 1)
{
	// do something
}
else if(choice == 2)
{
	// do something
}

Read More: