We were taught about if goto loops in school. The program given by instructor doesnt work. By doesnt work I mean that it gets compiled, but when i execute it, the output is nothing :
#include <iostream>
using namespace std;
int main() {
int i = 0;
prev: i++; // prev label
cout << "a ";
if(i < 20) { goto prev; }
return 0;
}
The actual loop to be implemented in was equivalent to this for loop:
for(int i = 0; i < 20; i++) {
cout << "a ";
}
Thank you!
Depending on how fast you are, you may not notice the programs output, because it does not wait for the user. It just closes. You should make it wait for you to observe it's runtime behavior:
#include <iostream>
using namespace std;
int main()
{
int i = 0;
prev: // prev label
i++;
cout << "a ";
if(i < 20)
{
goto prev;
}
// wait for the user to press [enter]
cin.get();
return 0;
}
The problem with the given program is that the value of i
is incremented at the beginning of the loop, and the check is performed at the end; thus, it will increment before the first iteration, and always execute at least one iteration. The following would more accurately reflect the given for
loop:
int main() {
int i = 0;
next: if(!(i < 20)) goto end;
cout << "a ";
i++;
goto next;
end: return 0;
}
For the most part, labels and gotos are rarely used - they result in harder to follow code, are only ways to make while/for/if blocks (such as here) about 99% of the time, and are most useful to know in order to better understand the compiler's job and how your code relates to the machine code it generates.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With