


Detailed explanation of the impact of C++ jump statement Goto on variable definition
Foreword
The goto statement is also called an unconditional transfer statement. Its basic form is as follows:
The statement label consists of a valid identifier and the symbol ";", where the naming rules of the identifier are the same as the variable name, that is, It consists of letters, numbers and underscores, and the first character must be a letter or underscore. After executing the goto statement, the program will jump to the statement label and execute the subsequent statements.
Usually goto statements are used in conjunction with if conditional statements. However, while the goto statement brings flexibility to the program, it also makes the program structure unclear and difficult to read, so it must be used rationally.
Problem found
We often encounter the problem that variables are defined after goto and the compilation fails under Linux (error message: crosses initialization of). In fact, you just need to pay attention. Today, after asking the seniors in the company, I also looked through some information and recorded it to deepen my memory. I hope it can be of some help to some people.
Error sample code:
#include <iostream> using namespace std; int main() { goto Exit; int a = 0; Exit: return 0; }
Error report:
[root@localhost c-c++]# g++ goto_study.cpp goto_study.cpp: In function 'int main()': goto_study.cpp:31: error: jump to label 'Exit' goto_study.cpp:29: error: from here goto_study.cpp:30: error: crosses initialization of 'int a'
Correct way of writing
cannot be said to be correct, it can only be said to be a way of compiling OK.
Go directly to the code:
Writing method 1:
Change the domain and become a local variable:
int main() { goto Exit; { int a = 0; } Exit: return 0; }
Writing method 2
Magical writing method:
int main() { goto Exit; int a; a = 1; Exit: cout << "a = " << a << endl; return 0; }
The key is that it can still be accessed! Result:
[root@localhost c-c++]# g++ goto_study.cpp [root@localhost c-c++]# ./a.out a = 1259648
Research
Magical writing method
After seeing two writing methods that can be compiled and passed, the most puzzling thing is that the second writing method can be compiled and passed, and can it still be used? ? ?
C++ regulations
Reference [1][2] mentioned the regulations in the C++ standard: > 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.
It means: if the execution path of a program jumps from point A in the code (a local variable x has not been defined) to another point B in the code (the local variable x has been defined and initialized when defined), then the compiler will report an error. Such a jump can be caused by executing a goto statement or a switch-case. Therefore, in the second way of writing, a is of int type, a POD type, and has not been initialized, so the compilation passes. However, it is obvious: if you use this variable a, the result is unknown. As the predecessor said, it is meaningless, it is better not to support it! If it is only used locally, it can be enclosed in curly braces! Some people on the Internet also said that although the C++ specification does not explicitly state that this is wrong, the provisions of the variable domain actually implicitly say that this approach is not advisable, see reference [4].
Implicit explanation
Goto can't skip over definitions of variables, because those variables would
not exist after the jump, since lifetime of variable starts at the point of
definition. The specification does not seem to explicitly mention goto must not
do that, but it is implied in what is said about variable lifetime.
-fpermissive flag
Reference [4] mentioned that the g++ compiler checks by default, you can set this flag of the compiler to become Warning, not implemented! ! !
After checking the information, the function of the fpermissive mark is to treat syntax errors in the code as a warning and continue the compilation process, so for the sake of safety, don’t think about it from this perspective, just code it!
POD type
Refer to [3]. According to the above C++ regulations, as long as it is a POD type and is not initialized, it can be compiled and passed. : Look at a paragraph of code:
#include <iostream> using namespace std; class A{ public: // 注意:和B不同的是有构造和析构函数, 所以编译报错 A(){} ~A(){} void testA(){ cout << "A::test." << endl; } }; class B{ public: void testB(){ cout << "B::test." << endl; } }; int main() { goto Exit; // int a = 1; // windows ok.linux failed! //A classA; // failed: B classB; // success: classB.testB(); Exit: classB.testB(); return 0; }Result:
[root@localhost c-c++]# g++ goto_study.cpp [root@localhost c-c++]# ./a.out a = 1259648 B::test.E
Summary:
1. The above code is compiled and executed in Windows and Linux; Compilation fails! Because A has a constructor and a destructor, it does not meet the conditions;
3. As for int a = 1; this way of writing can be passed under windows (msvc), but it is inconsistent with the C++ specification. Please explain! ! !
1. int, char, wchar_t, bool, float, double are POD types, these types are long/short and
The same is true for signed/unsigned versions;
2. Pointers (including function pointers and member pointers) are all POD types;
2. Do not skip definition and initialization of variables after goto. If it is a POD type, you can declare it first and then define it, and no compilation error will be reported. However, it is not recommended to use it this way. You can see that if the execution statement skips the assignment statement, the value of the variable is unknown and dangerous;
3. If there is a local variable after goto, it can be enclosed in curly braces to form a Local domain is safe.
The above is the entire content of this article. I hope the content of this article can be of some help to everyone's study or work. If you have any questions, you can leave a message to communicate.
For more related articles, please pay attention to the PHP Chinese website (www.php.cn)!

C# and .NET provide powerful features and an efficient development environment. 1) C# is a modern, object-oriented programming language that combines the power of C and the simplicity of Java. 2) The .NET framework is a platform for building and running applications, supporting multiple programming languages. 3) Classes and objects in C# are the core of object-oriented programming. Classes define data and behaviors, and objects are instances of classes. 4) The garbage collection mechanism of .NET automatically manages memory to simplify the work of developers. 5) C# and .NET provide powerful file operation functions, supporting synchronous and asynchronous programming. 6) Common errors can be solved through debugger, logging and exception handling. 7) Performance optimization and best practices include using StringBuild

.NETFramework is a cross-language, cross-platform development platform that provides a consistent programming model and a powerful runtime environment. 1) It consists of CLR and FCL, which manages memory and threads, and FCL provides pre-built functions. 2) Examples of usage include reading files and LINQ queries. 3) Common errors involve unhandled exceptions and memory leaks, and need to be resolved using debugging tools. 4) Performance optimization can be achieved through asynchronous programming and caching, and maintaining code readability and maintainability is the key.

Reasons for C#.NET to remain lasting attractive include its excellent performance, rich ecosystem, strong community support and cross-platform development capabilities. 1) Excellent performance and is suitable for enterprise-level application and game development; 2) The .NET framework provides a wide range of class libraries and tools to support a variety of development fields; 3) It has an active developer community and rich learning resources; 4) .NETCore realizes cross-platform development and expands application scenarios.

Design patterns in C#.NET include Singleton patterns and dependency injection. 1.Singleton mode ensures that there is only one instance of the class, which is suitable for scenarios where global access points are required, but attention should be paid to thread safety and abuse issues. 2. Dependency injection improves code flexibility and testability by injecting dependencies. It is often used for constructor injection, but it is necessary to avoid excessive use to increase complexity.

C#.NET is widely used in the modern world in the fields of game development, financial services, the Internet of Things and cloud computing. 1) In game development, use C# to program through the Unity engine. 2) In the field of financial services, C#.NET is used to develop high-performance trading systems and data analysis tools. 3) In terms of IoT and cloud computing, C#.NET provides support through Azure services to develop device control logic and data processing.

.NETFrameworkisWindows-centric,while.NETCore/5/6supportscross-platformdevelopment.1).NETFramework,since2002,isidealforWindowsapplicationsbutlimitedincross-platformcapabilities.2).NETCore,from2016,anditsevolutions(.NET5/6)offerbetterperformance,cross-

The C#.NET developer community provides rich resources and support, including: 1. Microsoft's official documents, 2. Community forums such as StackOverflow and Reddit, and 3. Open source projects on GitHub. These resources help developers improve their programming skills from basic learning to advanced applications.

The advantages of C#.NET include: 1) Language features, such as asynchronous programming simplifies development; 2) Performance and reliability, improving efficiency through JIT compilation and garbage collection mechanisms; 3) Cross-platform support, .NETCore expands application scenarios; 4) A wide range of practical applications, with outstanding performance from the Web to desktop and game development.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

WebStorm Mac version
Useful JavaScript development tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function
