Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - is it possible to decrement the max value of a for loop from within the for loop?

Tags:

c

for-loop

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.

like image 326
Tony Stark Avatar asked Apr 12 '10 21:04

Tony Stark


2 Answers

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.

like image 140
Mark Byers Avatar answered Sep 30 '22 00:09

Mark Byers


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.

like image 32
IVlad Avatar answered Sep 30 '22 01:09

IVlad