Max
Max

Reputation: 23

How can I cast while doing a division assignment?

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?

Upvotes: 2

Views: 74

Answers (3)

machine_1
machine_1

Reputation: 4454

A cast expression like (int)i is NOT an lvalue but rather an rvalue.

For readability, just update the value of i on a different line.:

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

Upvotes: 2

Acorn
Acorn

Reputation: 26194

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.

Upvotes: 5

dbush
dbush

Reputation: 225362

i by itself is an lvalue but (int)i is not. The result of the typecast operator is not an lvalue.

You'll need to break up the compound assignment operator:

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

Upvotes: 3

Related Questions