Search code examples
cunary-operatorinteger-promotionbinary-operators

Is unary minus equivalent to binop minus?


My C compiler gave a warning when using unary minus on an unsigned value, so I fixed the warning by doing a subtraction from 0 instead.

Now I wonder if the current code is equivalent to the original one:

uint32_t a, b; // assume b is initialized and non-zero

a =  -b   % b; // old code
a = (0-b) % b; // current code

My question is: for the same values of b will both lines of code yield the same result for a?


Solution

  • Usually, yes, unless on your platform uint32_t would be a narrow type. Then it would first be promoted to int and the negation would be made in that type.