3 ms·
The penultimate example tripped me up. I was under the impression that arithmetic conversions for binary operators only happened if the types of the operands we
by eridius 8y ago
The penultimate example tripped me up. I was under the impression that arithmetic conversions for binary operators only happened if the types of the operands were different. But reading the standard, and then actually experimenting with clang and __auto_type, does confirm that if the operands can be converted to int or unsigned int, then they will be (and that it will convert to int if int can represent all the values). That's really kind of nasty given the lack of wrapping overflow on signed integers.
This actually makes me wonder, if I do want wrapping overflow on signed integers in C, how do I request it? Is there some compiler builtin or stdlib function to say "please add/multiply/whatever these signed integers with overflow"?
- jforberg 8y agoYou have several options, at least if you are willing to stick with GCC/Clang. Passing -fwrapv will give you well-defined (wrapping) signed overflow, which is often the native machine behaviour anyway. If you are interested in catching overflow when it happens, you can use intrinsics like __builtin_add_overflow. These look at the overflow flags present on many machines to let you know if the operation overflowed so you can handle it any way you like. If you are of the opinion that overflow should never happen in your program, you can pass -ftrapv which asks the compiler to crash your program if overflow ever occurs.