-2

I came across a for loop statement in a C++ code, like this:

for (i=N, z=head; i>0;  a=z++, i--) {}

The type of z, head and a is a pointer to an array. a=z++ here really confused me. Could anyone give me some guidance on what a=z++ does in this for loop? And what is the relationship between z and a?

François Andrieux
  • 28,148
  • 6
  • 56
  • 87
HumbeCoder
  • 33
  • 2
  • Post complete, compilable code. –  Dec 04 '17 at 19:45
  • I assume you mean that `z`, `head` and `a` are pointers to elements in an array? Unless they are pointers to arrays within an array of arrays? – François Andrieux Dec 04 '17 at 19:46
  • You are right. They are pointers to elements in an array. I was wondering when the assign to a and increment of z happen inside the loop. Do you think I can change this for loop statement to : z=head; for (i=N; i>0; i--){ ....original operations...; a=z; z++; } ? – HumbeCoder Dec 04 '17 at 20:03

1 Answers1

2

Looks like you need to freshen up your C++ grammar.

In any context (loop or no loop) a = z++ means 'increment the value of z, and use the pre-incremented value of z to assign it to a.

In other words, in world of integers, if a is 100 and z is 10, after this executes z is 11, and a is 10.

In case those are pointers within arrays, the same logic applies - if z points to tenth element, after this statement a points to tenth, and z points to eleventh.

SergeyA
  • 61,605
  • 5
  • 78
  • 137
  • Thanks for your response. So can I change this for statement to this? z=head; for (i=N; i>0; i--){ ....original operations...; a=z; z++; } – HumbeCoder Dec 04 '17 at 19:52
  • @HumbeCoder There is practically no difference between `a=z++;` and `a=z; z++;`. – François Andrieux Dec 04 '17 at 20:06
  • @FrançoisAndrieux Thank you for your response. My confusion was kind of about when "a=z; z++;" will be executed. Since "i++" is executed at the end of the current iteration, I am guessing "a=z; z++;" should also be executed at the end of the for-loop, am I right? – HumbeCoder Dec 05 '17 at 00:48
  • @HumbeCoder You should read about [`operator,`](https://stackoverflow.com/questions/52550/what-does-the-comma-operator-do). A `for` loop as three components : the initialization, the condition and the iteration expression. They are separated by`i=N, z=head` for the initialization, `i>0` for the condition and `a=z++, i--` for the iteration expression. If you were to literally substitute `a=z++` with `a=z; z++` you would be introducing a semicolon which would break up your iteration expression. It would be more accurate to say, in this case, that `a=z++` is equivalent to `a=z, z++`. – François Andrieux Dec 05 '17 at 14:23
  • @FrançoisAndrieux Thank you so much for your guidance. – HumbeCoder Dec 05 '17 at 19:06