Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable used in loop condition not modified in loop body

I'm pretty new to C, but I am just trying to use a for loop to subtract 25 from the value of int change, assuming the value is already greater than 25. The error message I get is

"error: variable 'change' used in loop condition not modified in loop body [-Werror,-Wfor-loop-analysis]"

Which confuses me since don't I modify the variable 'change' in loop body by specifying change -25?

int main(void)
{
    float n;
    do
    {
        n = get_float("How much change do I owe you?: ");
    }
    while (n < 0);

    for (int change = n * 100; change >= 25; change - 25)
    {
        printf("%i", change);
    }
}
like image 519
atltbone Avatar asked Jul 31 '26 13:07

atltbone


1 Answers

(As of request, here is my comment as an answer)

Your loop for (int change = n * 100; change >= 25; change - 25) never modifies the variable change.

You simply subtract 25 from the value of of the variable change, returning the result and immediately discarding it again.

So instead of

change - 25

Use

change -= 25

Which is short for

change = change - 25

Please see the the Wikipedia page about the for loop to learn more about the syntax.

Excerpt from there:

for (initialization; condition; increment/decrement)
    statement

So the third part in the for loop should be the increment/decrement.

like image 170
Uwe Keim Avatar answered Aug 03 '26 04:08

Uwe Keim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!