Issue with absolute value of 64 bit integer

c, gcc

Solution

If the result of `llabs()` cannot be represented in the type `long long`, then the behaviour is undefined. We can infer that this is what's happening here - the out-of-range value 0x8000000000000000 is being converted to the value -9223372036854775808 when converted to `int64_t`, and your `long long` value is 64 bits wide, so the value 9223372036854775808 is unrepresentable.

In order for your program to have defined behaviour, you must ensure that the value passed to `llabs()` is not less than `-LLONG_MAX`. How you do this is up to you - either modify the "organisms" so that they cannot generate this value (eg. filter out those that create the out-of-range value as immediately unfit) or clamp the value before you pass it to `llabs()`.

Problem

This C code tries to find the absolute value of a negative number but the output also is negative. Can anyone tell me how to overcome this? ``` #include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <inttypes.h> int main() { int64_t a = 0x8000000000000000; a = llabs(a); printf("%" PRId64 "\n", a); return 0; } ``` Output ``` -9223372036854775808 ``` UPDATE: Thanks for all your answers. I understand that this is a non-standard value and that is why I am unable to perform an absolute operation on it. However, I did encounter this in an actual codebase that is a Genetic Programming simulation. The "organisms" in this do not know about the C standard and insist on generating this value :) Can anyone tell me an efficient way of working around this? Thanks again.

Original source