The effect of goto on variable definition in C + + Jump statement

Source: Internet
Author: User
Objective





The goto statement is also known as an unconditional transfer statement, which has the following basic form:



Statement designator by a valid identifier and symbol ";" , where the naming rules for identifiers are the same as variable names, which consist of letters, numbers, and underscores, and the first character must be a letter or an underscore. After the goto statement is executed, the program jumps to the statement label and executes the subsequent statement.



Usually the goto statement is used with the IF condition statement, but the GOTO statement gives the program flexibility, but also makes the program structure level unclear, and difficult to read, so it is reasonable to apply the statement.



Discover problems



We often run into problems that define variables after Goto and do not compile under Linux (Error message: crosses initialization of). In fact, as long as the attention is good, today asked a company after the predecessor, also turned over some information, record, deepen the memory, also hope to some people have some help.



Error Sample code:


#include <iostream>
using namespace std;
  
int main()
{
 goto Exit;
 int a = 0;
Exit:
 return 0;
}





Error:


[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 wording



Can not be said to be the correct wording, can only be said to compile OK to the wording.



Directly on the code:



Writing one:



Change the field to become a local variable:


int main()
{
 goto Exit;
 {
 int a = 0;
 }
Exit:
 return 0;
}








Two



Magical notation:


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





The key is that you can also access! Results:


[root@localhost c-c++]# g++ goto_study.cpp 
[root@localhost c-c++]# ./a.out
a = 1259648





Study



A magical notation



See two can be compiled through the writing, the most puzzling is that the two for the hair can be compiled through, but also can use???



C + + Provisions



reference to [note] refers to the provisions of the C + + standard: > It is possible-to-transfer into a block, and not in a-a-on-the-bypasses declarations with Init Ialization. A program this jumps from a point where a local variable with automatic storage duration are not in scope to a point where It is in scope is ill-formed unless the variable have POD type (3.9) and is declared without an initializer.



This means that if the execution path of a program jumps from point A in the code (a local variable x is undefined) to another point in the Code B (the local variable x is defined and initialized at the time of definition), the compiler will error. Such jumps can be caused by the execution of a goto statement, or by Switch-case. So, in notation two, a is an int type, is a pod type, and is not initialized, so the compilation passes. However, it is obvious: if you go to use this variable a, the result is unknown, as the predecessor said, there is no meaning, rather than support! If it is used only locally, it can be enclosed in curly braces! Some people on the internet have said that although the C + + specification is not clearly stated that this is wrong, but the scope of the variable is implicitly said that this practice is undesirable, see reference [4].



Implicit description



Goto can ' t skip over definitions of variables, because those variables would no exist after the jump, since lifetime of V Ariable starts at the point of definition. The specification does not seem to explicitly mention Goto must isn't do, but it's implied in what's said about Varia BLE lifetime.



-fpermissive Mark



Referring to [4] mentioned in the g++ compiler by default is checked, you can set the compiler of this flag into a warning, not practice!!!



I checked the information.-fpermissive tag function is: The code syntax error as a warning, and continue the compilation process, so on security, this angle do not think, or honest code brick!



Pod type



Reference [3], according to the above-mentioned C + + provisions, as long as the pod type, and no initialization can be compiled through.



Look at the code:


#include <iostream>
using namespace std;
class A {
public:
  // Note: Unlike B, there are constructors and destructors, so the compilation error
  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;
}





Results:


[root@localhost c-c++]# g++ goto_study.cpp 
[root@localhost c-c++]# ./a.out
a = 1259648
B::test.





Summary:



1, the above code under Windows and Linux are compiled and executed;



2, a ClassA in Windows and Linux are compiled do not pass! Because a has the structure and the destructor, does not satisfy the condition;



3, as for the int a = 1; Such a notation under Windows (MSVC) can be passed on the C + + specification does not match, to explain!!!



Here's the pod type (or the English bar):



1, int, char, wchar_t, bool, float, double are pod types, these types of Long/short and signed/unsigned versions are also;



2, pointers (including function pointers and member pointers) are pod types;



3, Enums enumeration type;



4, the const and ordinary variables of the pod are also;



5. Pod type class,struct and union are also. However, all members are required to be public, and there is no base class, no constructs, destructors, and virtual functions. Static members are also under these rules.



Summarize



1, it is best not to use Goto;



2, goto after do not skip the definition and initialization of the variable, if the pod type can be declared before the definition, will not compile the error. However, it is not recommended to use this, you can see that if the execution of the statement skipped the assignment statement, then the value of the variable is unknown, there is danger;



3, Goto back if it is a local variable, can be enclosed in curly braces to form a local domain, it is safe.



The above is the entire content of this article, I hope that the content of this article on everyone's study or work can bring certain help, if there is doubt you can message exchange.



For more related articles, please follow topic.alibabacloud.com (www.php.cn)!


  • 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.