Search code examples
c++while-loopfunction-pointers

Why while cycle causes problem with pointers?


I'm new in c++, I started studying pointers recently, I was trying to make a simple test program:

struct test {
    int a;
    double b;
    test *next;

    test() : a(0), b(0), next(nullptr) {}

    test(int v1, double v2) : a(v1), b(v2), next(nullptr) {}

    test(int v1, double v2, test *n) : a(v1), b(v2), next(n) {}
}

Than in the main I tried this:

int count = 0;
test *p;
test *p2 = new test();

do {
    cout << "Hello" << endl;
    cout++;
    if (count>5) {
        p = p2;
    }
}while(p==0);

while (p==0) {
    cout << "Hello" << endl;
    count++;
    if (count>5) {
        p = p2;
    }
}

The do-while cycle works, it prints the message as I want.

In the while cycle it doesn't, it didn't even bother to enter. I try to change the condition (from equal to not equal) "for some reason" and the terminal started to print the message in loop.

I even try to change, in the condition, '0' with 'nullptr', but the result is the same for both cycles. I try to print the location of the second pointer, p2, and it's in memory. Where I'm doing wrong?


Solution

  • When you have

    do{...}while(p == 0)
    

    it means that the cycle should execute until p is different from 0, if p is equal to 0 the loop will continue, if it's different it will exit the loop.

    So if it is ended, p will be different from 0.

    The next loop will only execute if p is equal to 0, see what I mean?

    Here is a working sample