Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can we implement if -goto loops in C++? [closed]

Tags:

c++

loops

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!

like image 956
Max Payne Avatar asked Jan 09 '23 01:01

Max Payne


2 Answers

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;
}
like image 109
nvoigt Avatar answered Jan 20 '23 19:01

nvoigt


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.

like image 32
David Avatar answered Jan 20 '23 21:01

David