Do I need to worry or think too much about combining signed and unsigned integers or does the compiler sort everything out on its own? For example in the following code:
int thing1 = 30000;
unsigned int thing2 = 40000;
Stuff(thing2 - thing1);
void Stuff (int newThing) {}
I suspect it does the subtraction as an unsigned int and since the result will fit into the new int everything goes smoothly?
The compiler will do just as you tell it what to do. It doesn't sort things out of its own. So if your code might cause overflow, it probably will and the compiler doesn't care.
It means you have to know what you do. When you have even the smallest doubt, use long or float or cast the value to the proper variable type.
Thanks for the quick responses. Unfortunately I'm not at my desk where I could try your code example, but thanks I will try it later.
I found in the reference section that the subtraction will use the larger data type so that should be OK, but I can't find anything about what happens when I send the value to the function. So can I assume that process works along the lines of assignment using "=" and I should recast it before sending it? Like the following:
The function Stuff() requires an integer, so it is cast to an integer anyway.
Perhaps this is also possible: Stuff( (int) thing2 - thing 1);
In the end, it all depends on the value of thing2.
You set it to 4000, but can it be 50000 ? (larger than 'int').
You have to know what value it can get, before we can say if the subtraction makes any sense.
In general the differences are in certain operators, such as /, % >>, and comparisons
where results are sign-dependent. Since 2's complement arithmetic is used many
operators are the same for signed and unsigned operands, such as +, -, <<
This is because at the bit level there 2's complement add/subtract are the same
as unsigned add/subtract.
Also casting an 8 bit type to int will depend on whether the 8 bit type is signed
or not.