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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With