As usual on SO, the "accepted" answer completely misses the mark. The standard is worded that way so things like short x = 32767, y = 5000; int z = x + y will naturally work. It doesn't mean the implementation has to actually do any widening if it doesn't make any observable difference.
Any sane compiler would realise that the promotion is useless in the case of addition and subtraction with shorts because the arithmetic turns out the same either way. Adding an int to a short and then assigning to a short should cause a warning, because there is the possibility of truncation.
Of course, GCC is not a sane compiler.
Name:
Anonymous2016-10-01 16:41
Did you know C standard silently promotes integers to larger size, because "its good for you".
Yes, I did. The rule is actually simple: C can only do integral arithmetic on int and long (if required) types, and not on short or char. The Standard implies a load-store machine, where any integral data gets loaded into either an int- or long-sized register (sign or zero extending if necessary), then the calculation is done and then the result gets written back to memory (truncating it if necessary). RAM (usually 8, 16, 32 or 64 bit words) -> CPU (usually 32 or 64 bit words nowadays) -> RAM again (...) 'So, whats the point with chars and shorts, anyway?', you may ask. To save memory space, basically. Char (array) is usually used for storing strings and short for storing numbers in the up to 10000 or so range (e.g. list of indices for a small-ish array). The same *should* go for floats and doubles, too, but is not required by the standard: floats for storing, doubles for calculations.
>>5 Introduce a double into a calculation involving shorts and ints, and the final result will also be a double.
The standard leaves a lot unspecified, but if you add two chars together and store the result in a char, a compiler should be smart enough to figure out that no widening is needed because it doesn't matter one bloody bit.
Name:
Anonymous2016-10-01 17:40
>>6 The Ada SPARK compiler is smart enough to suggest a a/2 + b/2 in place of (a + b)/2 because the former is safer overflow-wise. The GCC isn't smart enough to understand that adding two shorts should result in a short.
Name:
Anonymous2016-10-01 18:17
>>6 GCC seems to emit correctly sized ops only for unsigned operands and long/long long ops for signed. Maybe we're forgetting something? Here's my test file (compile with 'gcc -S'): #include <stdint.h> #define CATN(t) F ## t #define FN(T) T CATN(T)(T u, T v) {return u / v;}