Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I cast while doing a division assignment?

Tags:

c

I am practicing C basics for my exam and encountered a tricky situation while doing a simple for loop:

int main()
{
    for( double i = 9.999; i > 0; )
    {
        printf("%d ", ((int)i) /= 2);
    }

    return 0;
}

I get an error:

error: lvalue required as left operand of assignment
         printf("%d ", ((int)i) /= 2);
                                ^~

Isn't (int)i an lvalue? Or how could you rewrite it to get the output: 4 2 1 0?

like image 573
Max Avatar asked Feb 27 '26 08:02

Max


1 Answers

Isn't (int)i an lvalue ?

i is, (int)i isn't.

Or how could you rewrite it to get the output: 4 2 1 0?

The best you can do is be clear and separate the statements:

i = (int)i / 2;
printf("%d ", (int)i);

Note that you cannot use i /= 2 in the first one since then you will not get to zero quickly by truncating.

like image 75
Acorn Avatar answered Mar 02 '26 02:03

Acorn



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!