Reading some topics I found this piece of code, and I'm wondering, how does it works, because it prinst:
5
2
The code:
static int a = 7;
int test()
{
  return a--;
}
int main()
{
  for(test();test();test())
  {
    cout << test() << "\n";
  }
  return 0;
}
                Order of operations, as presented:
a is globally initialized on startup. to 7test() decrements a to 6, then returns the prior value (7), which is ignored. test() decrements a to 5, then returns the prior value (6) which passes the non-zero test so the for-loop can continue.cout statement; test() decrements a to 4, returning the prior value (5) which is sent to cout.test() decrements a to 3, returning the prior value (4), which is ignored.test() decrements a to 2, returning the prior value (3), which passes the non-zero test and the loop continues.cout statement; test() decrements a to 1, returning the prior value (2) which is sent to cout.test() decrements a to 0, returning the prior value (1), which is ignored.test() decrements a to -1, returning the prior value (0), which fails the non-zero test and the loop terminates.Now. Start that loop at 6 or 8 and see what happens. =P
A for loop of the form:
for (a; b; c) {
    // stuff
}
is equivalent to this:
{
    a;
    while (b) {
        // stuff
        c;
    }
}
                        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