Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does this for-loop actually work?

Tags:

c++

c

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;
}
like image 942
ddacot Avatar asked Jan 06 '13 12:01

ddacot


2 Answers

Order of operations, as presented:

  1. a is globally initialized on startup. to 7
  2. Initializer of for-loop is hit first, test() decrements a to 6, then returns the prior value (7), which is ignored.
  3. The test case of for-loop is hit, test() decrements a to 5, then returns the prior value (6) which passes the non-zero test so the for-loop can continue.
  4. The cout statement; test() decrements a to 4, returning the prior value (5) which is sent to cout.
  5. The increment-statement of the for-loop is executed. test() decrements a to 3, returning the prior value (4), which is ignored.
  6. The test case of the for-loop is hit. test() decrements a to 2, returning the prior value (3), which passes the non-zero test and the loop continues.
  7. The cout statement; test() decrements a to 1, returning the prior value (2) which is sent to cout.
  8. The increment-statement of the for-loop is executed. test() decrements a to 0, returning the prior value (1), which is ignored.
  9. The test case of the for-loop is hit. 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

like image 157
WhozCraig Avatar answered Sep 29 '22 18:09

WhozCraig


A for loop of the form:

for (a; b; c) {
    // stuff
}

is equivalent to this:

{
    a;
    while (b) {
        // stuff
        c;
    }
}
like image 26
Oliver Charlesworth Avatar answered Sep 29 '22 20:09

Oliver Charlesworth