abs() function implementation issue in C++

(2550 Views)


In this article we will discuss why abs() on local computer works as expected, i.e. produces floating point results, but on server the end results are truncated to an integer.

On Local the results are as below:

abs(-1.1341234) = 1

On server the results are as below:

abs(-1.1341234) = 1.1341234

Cause of the problem:

Basically this occurs as developers tend to overlook the impact of overloading of functions in C++. C defines abs() function in the header file to get the absolute values of an integer, but C defines the function fabs() in the header to get the absolute value of a double. In case of C++, all these function are inherited and the abs() function is overloaded.

Solution:

While calling and overloaded function like abs() in C++, you have to ensure that you include the correct header. There are two options for these:

  • #Include <cmath.h> : Include <cmath.h> header and then invoke std:abs(). In this case the results will be abs(double).
  • #Include <cstdlib.h> : Include <cstdlib.h> header and then invoke abs(). In this case the results will be abs(int)

On a side note, always enable all warning while compiling to catch these errors early.

Solution Worked 0 UpvotesUpvote

        

Solution Didn't Worked 0 DownvotesDownvote



Comments



Search

Play 2048 Game Online

Play Duckhunt Online

Need Help?

Looking for any Software or Tutorial?
Don't Worry, we will find it for you
Contact Now

Search Tags