This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

Using unsigned with signed int

I have a signed integer which I have to assign to an unsigned one after addition with unsigned one.

Like

int16_t x = -9;
uint16_t y = 11;

if(x < y)
{ y = y+x;
}

How to ensure that it always result in write opeartion, because signed & unsigned operation scombined form wrong values.

Parents
  • "always result in write operation" is a completely different from how to handle a mix of signed and unsigned.

    Unless you play with volatile or similar, the compiler will always check if you make use of the result before it decides if it should write down any value or not.

    About signed/unsigned - have you looked at the C standard for type promotions when missing signed/unsigned? If you convert -9 to an unsigned value and add that value with 11 and store to an unsigned variable you will get a completely different result compared to if you convert 11 to signed, and subtract 9 from 11 before you store the result.

    So in the end, you must learn when to insert manual type casts when your goal is a completely different one from the language standard rules for making left and right side of an operation compatible.

    Another issues is of course what to expect if x was -11 and y was 9 when you store that result in a signed or unsigned target variable.

Reply
  • "always result in write operation" is a completely different from how to handle a mix of signed and unsigned.

    Unless you play with volatile or similar, the compiler will always check if you make use of the result before it decides if it should write down any value or not.

    About signed/unsigned - have you looked at the C standard for type promotions when missing signed/unsigned? If you convert -9 to an unsigned value and add that value with 11 and store to an unsigned variable you will get a completely different result compared to if you convert 11 to signed, and subtract 9 from 11 before you store the result.

    So in the end, you must learn when to insert manual type casts when your goal is a completely different one from the language standard rules for making left and right side of an operation compatible.

    Another issues is of course what to expect if x was -11 and y was 9 when you store that result in a signed or unsigned target variable.

Children