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.
"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.
Did you mean, "right operation"?
I found this :
If an operation involves both signed and unsigned integers, the situation is a bit more complicated. If the unsigned operand is smaller (perhaps we're operating on unsigned int and long int), such that the larger, signed type could represent all values of the smaller, unsigned type, then the unsigned value is converted to the larger, signed type, and the result has the larger, signed type. Otherwise (that is, if the signed type can not represent all values of the unsigned type), both values are converted to a common unsigned type, and the result has that unsigned type.
Few question:
1. It says "if the signed type can not represent all values of the unsigned type), both values are converted to a common unsigned type, and the result has that unsigned type".
So does that mean before result is used, signed in converted to unsigned & then added to form result?
2. I have one problem where I have two same width vars: uint16_t & int16_t
so what I did:
uint16_t temp; int16_t temp2; //......... if(temp2 > 0) { temp = temp + (uint16_t)temp2; } else { temp2 = -temp2; temp = temp - (uint16_t)temp2; }
3.Also how to type cast from int to uint. Is it right method to do
Like :
int16_t temp2; uint16_t temp; if(temp2 < 0) // for safe tytpe casting, will limit -ve range, +ve range is auto temp2 = 0; temp = (uint16_t) (temp2);