3 ms·
There is no absolute value for -128 (or 0xff) in the range of int8_t because 128 is not in 0..127. The error is not the logic or the compiler but rather the ret
by CalChris 5y ago
There is no absolute value for -128 (or 0xff) in the range of int8_t because 128 is not in 0..127. The error is not the logic or the compiler but rather the return type which should be (at least) int16_t. Indeed simply changing the return to int16_t gives
abs(-128) = 128
abs(-127) = 127
abs( 0) = 0
abs( 126) = 126
abs( 127) = 127
- chrisseaton 5y agoDoes the type flow back from the return type to the negation operator? I had no idea C worked like that! I would have assumed -x was the same type as x and then it was converted for the wider return type.
- skitter 5y agoI believe x gets promoted to int, negated and then narrowed to the return type.
- CalChris 5y agoThat is what the LLVM IR says happens: https://godbolt.org/z/4aexEK3aE https://godbolt.org/z/4aexEK3aE
- caf 5y agoArithmetic operations are never done in a type narrower than int. int8_t is necessarily narrower than int (int must be able to represent at least the range -32767..32767), so in -x the x is promoted to int, then negated.
- deleted 5y ago[deleted]
- nabla9 5y agoIt just moves the problem. You can keep pushing the problem up to int64_t, but it does not go away. abs(-9223372036854775808) = -9223372036854775808 abs(-9223372036854775807) = 9223372036854775807 abs( 0) = 0 abs( 9223372036854775806) = 9223372036854775806 abs( 9223372036854775807) = 9223372036854775807