Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining compound operators

Tags:

c

operators

I'm only a casual user of C, when programming for micros like Arduino, but I'm interested in bettering my understanding of the vernacular.

I know that you can shorthand things like x = x % 10 to x %= 10, and x = x + 1 to x += 1. But I couldn't wrap my head around compounding both parts of this:

x = (x + 1) % 10

If that's possible, what does it look like? (x += 1) %= 10 ? That seems... if not wrong, then confusing.

like image 986
Jim Mack Avatar asked Oct 17 '25 01:10

Jim Mack


1 Answers

The expression (x += 1) %= 10 is not legal in C. The result of an assignment operator, whether = or one of the compound assignment operators, is not a lvalue. Loosely speaking, this means it can't appear on the left side of an assignment.

That statement would have to be broken up in two parts:

x += 1;
x %= 10;

As an aside, (x += 1) %= 10 is valid in C++.

like image 122
dbush Avatar answered Oct 19 '25 15:10

dbush



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!