The code:
6 void
7 reverse(char *digits, int len, string &reversed) {
8 cout << "digits = " << digits << ", len = " << len << endl;
9
10 for (int i = len; i--; i >= 0) {
11 cout << "digits[" << i << "] = " << digits[i] << endl;
12 reversed.push_back(digits[i]);
13 }
The output:
digits = 1234567890, len = 10
digits[9] = 0
digits[8] = 9
digits[7] = 8
digits[6] = 7
digits[5] = 6
digits[4] = 5
digits[3] = 4
digits[2] = 3
digits[1] = 2
digits[0] = 1
reversed = 0987654321, len = 10
The question:
how comes the for() loop output starting at digits[9] rather then [10]?
Environment:
the compiler is "g++ (GCC) 4.1.2 20080704 (Red Hat 4.1.2-48)" on RHEL5.
Last edited on
Well, you are using the value of len, so it's because len is 9. >_>
for (int i = len; i--; i >= 0)
You got part of the for statement reversed:
for(int i = len; i >=0; --i)
But if the array has 10 elements, remember the last one is digits[9].
This is almost certainly incorrect
for (int i = len; i--; i >= 0)
The i >= 0 does nothing in that position
It works however because of this test i-- post decrement operator
This test checks i before decrenting it by 1.
If it was the pre-decrement operator --i it wouldn't have worked properly.
So, this code shows the programming making a mistake and the code still works (by accident)
Last edited on
yeah, you are right, statement is reversed .... my blinded eyes :( this works:
for (int i = len-1; i >= 0; i--)