Home Backend Development C#.Net Tutorial Detailed explanation of the impact of C++ jump statement Goto on variable definition

Detailed explanation of the impact of C++ jump statement Goto on variable definition

Dec 14, 2016 pm 05:15 PM

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;
}
Copy after login

Error report:

[root@localhost c-c++]# g++ goto_study.cpp 
goto_study.cpp: In function &#39;int main()&#39;:
goto_study.cpp:31: error: jump to label &#39;Exit&#39;
goto_study.cpp:29: error: from here
goto_study.cpp:30: error: crosses initialization of &#39;int a&#39;
Copy after login

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;
}
Copy after login

Writing method 2

Magical writing method:

int main()
{
 goto Exit;
 int a;
 a = 1;
Exit:
 cout << "a = " << a << endl;
 return 0;
}
Copy after login

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
Copy after login

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;
}
Copy after login

Result:

[root@localhost c-c++]# g++ goto_study.cpp 
[root@localhost c-c++]# ./a.out
a = 1259648
B::test.
Copy after login
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! ! !


The following are POD types (let’s read in English):


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;

3. enums enumeration types; 4. POD’s const and ordinary variables are also;


5. The same applies to POD type class, struct and union. But all members are required to be public, and there is no base class, no constructor, destructor and virtual function. Static members are also subject to these rules.


Summary


1. It is best not to use goto;

       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)!


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1253
24
How to define variables in Python? How to define variables in Python? Jun 04, 2023 am 10:02 AM

In Python, variables can be understood as containers for storing data. When we need to use or manipulate data, we can define variables to store the data so that we can easily call and process the data. The following will introduce how to define variables in Python. 1. Naming rules In Python, the naming rules for variables are very flexible and usually need to follow the following rules: variable names consist of letters, underscores and numbers, and the first part cannot be a number. Variable names can use uppercase and lowercase letters, but Python is case-sensitive. variable name

What is the meaning of goto statement in c language What is the meaning of goto statement in c language Dec 22, 2022 pm 06:00 PM

In the C language, the goto statement is called an unconditional transfer statement, which allows unconditional transfer of control to a labeled statement within the same function; the syntax is "goto label;...label: statement;", where label can be anything except C Plain text other than keywords, which can be set before or after the goto statement in a C program.

How to use goto in go language How to use goto in go language Nov 23, 2022 pm 06:40 PM

In the Go language, the goto statement is used to jump unconditionally to a specified line in the program; it uses labels to make unconditional jumps between codes. goto is followed by a label. The meaning of this label is to tell the Go program which line of code to execute next. The syntax is "goto label;... ...label: expression;". goto breaks the original code execution order and jumps directly to the specified line to execute the code; the goto statement is usually used in conjunction with conditional statements and can be used to implement functions such as conditional transfers, forming loops, and jumping out of loop bodies.

Assignment methods and differences when defining variables in Golang functions Assignment methods and differences when defining variables in Golang functions May 17, 2023 pm 07:01 PM

Golang is a fast, efficient, and modern programming language that automatically checks types at compile time and has features such as concurrency and memory safety, so it is favored by more and more developers. In Golang, we often need to use functions to encapsulate business logic, and the assignment method when defining variables in functions is a common problem. This article will explain this problem in detail and analyze the differences. Variable definition In Golang, variables can be defined in two ways: var and :=. Among them, var square

How to define variables and constants in PHP How to define variables and constants in PHP May 11, 2023 pm 04:03 PM

PHP is a widely used programming language with excellent scalability and practicality. In PHP, variables and constants are two very important concepts. They can be used to store and represent values ​​and store important information. In this article, we will introduce in detail how to define variables and constants in PHP to help beginners get started quickly. 1. Define variables A variable is a name or identifier used to store a value. In PHP, the definition of variables can be divided into three steps: variable declaration, variable assignment and variable use. Below we detail

Improve programming efficiency: master the application of jump statements in Go language Improve programming efficiency: master the application of jump statements in Go language Mar 21, 2024 pm 05:03 PM

Improve programming efficiency: Master the application of Go language jump statements. In Go language programming, jump statements are a commonly used control statement, which can help us realize jumps and control of code logic and improve programming efficiency. Mastering the use of jump statements allows us to handle various complex logics more flexibly, reduce code redundancy, and improve code readability and execution efficiency. This article will introduce commonly used jump statements in the Go language and illustrate their application through specific code examples. 1.break statement The break statement is used to jump out of the current loop.

How to solve Python's repeated function variable definition error? How to solve Python's repeated function variable definition error? Jun 25, 2023 am 11:59 AM

Duplicate definition errors of function variables in Python are a common problem. When a variable with the same name is repeatedly defined in a function, Python will throw a "localvariable'xxxx'redefined" error. This error is usually caused by duplication of variable names inside and outside the function. In Python, variable scope is divided into local scope and global scope. When a variable is defined in a function, the variable defaults to a local variable and can only be used in that function.

Golang variable definition specifications and techniques Golang variable definition specifications and techniques Jan 13, 2024 pm 03:43 PM

Overview of specifications and techniques for variable definition in Golang: In Golang, variables are the most basic data storage unit in the program. Proper use of variable definition conventions and techniques can improve code readability, maintainability, and performance. This article will introduce some specifications and techniques for variable definition in Golang, and provide specific code examples. Naming conventions for variables: In Golang, there are certain conventions for naming variables. Variable names should use camelCase, with the first letter lowercase. If it is a private variable, it should be named in camel case.

See all articles