Reputation: 23
I wanted to ask if this is correct goto loop in C++ :
#include <iostream>
int main() {
int i=0, a=0;
this:std::cout << i << " is less than 10\n";
i++;
if( i<10) goto this;
return 0;
}
I have this in very old c++ book, and don't know if it is correct in present day C++.
Note: It compiles successfully on Linux mint using g++.
Upvotes: 0
Views: 217
Reputation: 311028
My advice is forget that C++ has the goto statement and never use it. :) When the goto statement is used the program loses its structure and as result such programs are difficult to read. Also one goto statement usually produces another goto statements in the same program because the discipline of writing the structured code is broken.:) And usually it is dificult to modify such programs.
The program that you showed can be rewritten the following way
#include <iostream>
int main()
{
const int N = 10;
int i = 0;
do
{
std::cout << i << " is less than " << N << "\n";
} while ( ++i < N );
return 0;
}
Or the following way
#include <iostream>
int main()
{
const int N = 10;
for ( int i = 0; i < N; i++ )
{
std::cout << i << " is less than " << N << "\n";
}
return 0;
}
Though in general case when N can be initially set to 0 the two programs are not equivalent.
Take into account that variable a is not used in your porgram and its declaration should be removed.
Also it is a bad idea to use keywords as identifiers. this is a reserved keyword in C++.
Upvotes: 1
Reputation: 254501
Arguably, there's no proper way to use goto
. Use a structured loop instead:
for (int i = 0; i < 10; ++i) {
std::cout << i << " is less than 10\n";
}
If you insist on using goto
, then you'll have to change the name of the label. this
is a keyword in C++, and can't be used as an identifier.
Upvotes: 7