[C/C ++] error: Jump to case label

Source: Internet
Author: User
Tags variable scope

Problem

The following is not allowed:

Switch ()
{
Case 1:
Int A = 6;
// Stuff
Break;

Case 2:
// Stuff
Break;
}


The following is allowed:

Switch ()
{
Case 1:
{
Int A = 6;
// Stuff
}
Break;

Case 2:
// Stuff
Break;
}

 

A piece of code from the actual project is simplified as follows:
Switch (t)
{
Case 0:
Int A = 0;
Break;
Default:
Break;
}
Is there any problem? No. Compile it with the compiler ......
Hmm ?! An error "error c2361: initialization of 'A' is skipped by 'default' label" is returned ". How is this possible?
After several attempts, I realized that in the C ++ convention, in block statements, the scope of an object starts from the declaration statement of the object until the completion of the block statement, that is to say, the statement after the default label can use object. If the program jumps from switch to default during execution, object A is not correctly initialized. Ensure that object initialization is an important design philosophy of C ++, so the compiler will strictly check this violation, as in the above example code, the default statement is not followed by, however, given that code changes may be accidentally used in the future, the code is blocked.
After understanding the cause, it is easy to solve the problem. You only need to explicitly limit the scope of object.
Switch (t)
{
Case 0:
{// Added for fix problem
Int A = 0;
Break;
} // Added for fix problem
Default:
Break;
}
If you need to use object A in the entire switch statement, move int A = 0 to the switch statement. However, from the original statement, its intention does not seem to be like this, so we recommend the previous solution.

Is it over? No. Let's continue to examine the exact meaning of "initialization" (that is, initialization) in the error message. C ++ attaches great importance to initialization, so it often creates an illusion that the object must be initialized at the definition. What is the actual situation? Let's prove it with an instance.
Switch (t)
{
Case 0:
Int;
A = 0;
Break;
Default:
Break;
}
Compilation. No error is reported this time. Obviously, int A; defines the object but does not initialize it. Otherwise, the original error should be reported.
Let's look at the User-Defined type.
Class B
{
};

Switch (t)
{
Case 0:
B;
Break;
Default:
Break;
}
The compilation result is correct, so the class that does not provide the constructor still has no initialization process.
If the constructor is added to the class, the situation is different.
Class B
{
Public: // added for initialization
B () {}// added for initialization
};
In this way, the original error can be reproduced. It turns out that with the constructor, the compiler will initialize and perform security checks on it.

From the above experiment, we can intuitively experience some basic C ++ concepts and principles, and increase understanding depth.
1. int A = 0; both declaration and definition, and initialization; int A; declaration or definition depends on context, but Initialization is not included if definition is used; a = 0; only the value assignment statement. The object before this sentence already exists.
2. To avoid unnecessary overhead, the compiler does not provide the initialization process by default, that is, when the programmer does not explicitly indicate in the code. For some classes that need to be initialized, provide the constructor. A c ++ design philosophy is revealed here: you usually have multiple choices, so please control the code accurately, the benefit is that you can freely choose program features such as security, speed, and memory overhead of configurations.
3. pay close attention to the use of labels in the program, especially regular labels such as case and default. Otherwise, they may damage the correct state of the object. If object initialization is provided, you can get additional help from the compiler.

Problem:
1>
"
If the program jumps from switch to default during execution, object A is not correctly initialized. Ensure that object initialization is an important design philosophy of C ++, so the compiler will strictly check this violation, as in the above example code, the default statement is not followed by, however, given that code changes may be accidentally used in the future, the code is blocked.
"
Does it still take into account the possibility of accidental use of code changes in the future?

2>
Class B
{
};
Why did the author say that no initialization was made when declaring a B object? Didn't the class use its default constructor to initialize the object without declaring the constructor? Why did the author say there is no initialization?

3>
Why is there a problem without initialization? Must all objects in C ++ be initialized? That's not the case.
The author seems to be saying that .!

//////////////////////////////////////// //////////////////////////////////////// //////////////////////////////////////// //

 

First of all, we must acknowledge that the author has raised this question very well. Many people will encounter this situation. However, his understanding of this problem may be a misunderstanding or inadequate.
The following is my analysis code:
switch (t){case 0:    int a = 0;    break;default:    break;}

The error message in G ++ is:
Case_init.cpp: 9: Error: Jump to case label
Case_init.cpp: 7: Error: crosses initialization of 'int'
First, the author mentioned that the problem lies in the scope of the local variable or the automatic variable. The point is very good. The local variable scope is only between curly brackets. So solution 1: code:

 switch (t){case 0:  { //added for fix problem     int a = 0;     break;  } //added for fix problemdefault:     break;}

The problem is solved. In the new constraints, variable a works well and implements the intention correctly. Solution 2: code:

switch (t){case 0:    int a;    a = 0;    break;default:    break;}

That's right. It seems that both solutions have completed the goal and are equivalent. So the author moved his attention to the initialization issue and held it apart. At the end, he did not know why initialization was possible or sometimes not.
As a matter of fact, it is completely clear that I modified the program and added several print statements: code:

# Include <stdio. h> int main () {printf ("enter a number:"); int t; scanf ("% d", & T); Switch (t) {Case 0: int A; printf ("/n a = % d/N", a = 0); break; Case 1: printf ("/n a = % d/N ", a = 1); break; default: printf ("/n a = % d/N", A = T); break ;}}

After compilation, run the command to see if everything is normal. It may be strange that int A is declared in case 0! If 1 is selected during running, will it skip? How can it be used in Case 1 and default?
I don't know whether you select 0 or not. The defined local variable A is within its scope (from declaration to ending curly braces ).
Are valid.
Here we should understand why the compiler responds to int A = 0; Initialization!
Although you know that A is used only in case 0, A is not used in Case 1 or default, but the compiler doesn't understand your mind,
To avoid unnecessary troubles when using this variable elsewhere, make an error reminder. As for the example of the class below, the truth is the same.
The so-called believe in books is not as good as having no books, not to mention the Masters' handwriting. We have a longer eye and more hands-on work to help analyze problems.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.