tags:

views:

247

answers:

4

for example:

void decrement(int counter) {
    counter--;
}

int counter = 20;
for (int i = 0; i < counter; i++) {
    for (int j = 0; j < counter, j++) {
        decrement(counter);
    }
}

ideally, what i'd like to see is the counter var being decremented every time the for loop is run, so that it runs fewer than 20 iterations. but gdb shows that within decrement() counter is decremented, but that going back to the for loop counter actually stays the same.

+9  A: 

Yes it is possible:

for (int i = 0; i < counter; i++) {
    counter--;
}

The reason why it doesn't work in your example is because you are passing by value and modifying the copy of the value. It would work if you passed a pointer to the variable instead of just passing the value.

Mark Byers
It helps to think about how this is compiled: counter is read and checked before each iteration, so a modification within the loop just changes that check. One way to convince yourself of this is to convert it to a while loop.
WhirlWind
+5  A: 

You can also use pointers so the value remains changed outside of the decrement function:

void decrement(int *counter) {
    (*counter)--;
}

int counter = 20;
for (int i = 0; i < counter; i++) {
    for (int j = 0; j < counter; j++) {
        decrement(&counter);
    }
}

Or just do counter-- instead of calling the decrement function.

IVlad
+1 - nice examples
dboarman
+1  A: 

As Mark has shown it is possible, but its one of those don't do it

While you can all sorts of tricky things with for loops, its best not to if you can write it in a more clear fashion.

Keep code short for understanding, not code space. Code is for humans to read, not to care about how much space it is taking up. (In the general case anyways)

Pyrolistical
+1! This is a bad practice in almost any language. As others have said, if one absolutely requires this kind of logic, use a while().
Kevin Little
A: 

All you do is simply counter --;, you don't need to do anything special, especially if it adds to the complexity of the code without providing any additional functionality that the language can't already accomodate.

Jason Edwards