Weird behaviour of abs in C/C++

Hi @all,

At midnight 4 am,

I was solving the question CM01 got frustrated finding the mistake in this simplest solution in C language and C++ language which went on going WA’s, later on thought to move to C++ and got AC with abs of algorithm in stl

AC solution using abs from STL C++ using abs from algorithm

Finally on single stepping realize that the abs was giving weird answers in C & C++ of stdlib.h header file so did not understood the weird behavior? Does anyone know why abs does not give correct answers in C/C++ of stdib.h while it works properly in C++ from stl.

Final AC solution in C without using abs --> C Solution

P.S. Do check the input/output to understand why abs gives different answers in C than C++.

Sample Case:



100000000 100000000



Thanks in advance!

The cstdlib header file abs doesn’t have a defined return type for floating point values. That is if you write abs(7.42) with cstdlib it’ll return integer 7. However with cmath header file it returns 7.42.
This is for your reference. You can clearly see here that the cstdlib abs doesn’t have a double return type. Try out for yourself. To see the difference.


Hi thank you for your link i understood my mistake, for stlib.h header file to use abs for long long integers we have llabs and not abs

Correct solutions link with abs from stdlib.h → CodeChef: Practical coding for everyone

1 Like