cavravr-gccunary-operator8-bit

unary operator in avr: undefined behavior?


I had the issue that

voltage = voltage*2/3; and voltage *= 2/3;

gave different results. The variable is uint16_t and is running on an 8bit AVR microcontroller First statement gave the correct result, second statement always returned 0.

Some friends of mine told me that unary operators should not be used in general which made me think since I also use things like PORTC &= ~(1 << csBit);. For compiling, I use avr-gcc if that might give you an idea.

Thanks in advance for your help

edit#1:

OK, I understood that = is not an unary operator. Also the underlying difference is that '''=''' is starting from the right and ''''*, /''' is starting from left.

I guess for uints, both statements are not correct and I would have to write voltage = (uint16_t)((float)voltage*(float)2/3)

and thanks @Lundin for pointing out how to correctly react to replies


Solution

  • voltage = voltage*2/3 multiplies voltage by 2, divides by 3, and stores the result in voltage.

    voltage *= 2/3 divides 2 by 3, multiplies the result by voltage and stores the result of that in voltage. Integer division truncates, so 2/3 produces zero.

    None of those are unary operators.