I was having some problems with a sample code i was testing, since my abs function was not returning the correct result. abs(-2) was outputing -2 (this, by the way, is supos
gcc
optimizes the call to abs()
to use its built-in abs()
. So if you use the -fno-builtin
option (or define your abs()
as returning int
), you'll notice you get the correct result. According to this (quoting):
GCC includes built-in versions of many of the functions in the standard C library. The versions prefixed with _builtin will always be treated as having the same meaning as the C library function even if you specify the -fno-builtin option. (see C Dialect Options) Many of these functions are only optimized in certain cases; if they are not optimized in a particular case, a call to the library function will be emitted.
Had you included stdlib.h
, which declares abs()
in the first place, you'd get an error at compile time.
Sounds a lot like this bug, which is from 2007 and noted as being fixed.
You should of course try to compile without GCC's intrinics, i.e. pass -fno-builtin
(or just -fno-builtin-abs
to snipe out only abs()
) when compiling.
GCC is playing tricks on you due to the interplay of the following:
abs
is a built-in function;abs
to return unsigned int
while the standard (and built-in) abs
returns signed int
.Try compiling with gcc -fno-builtin
; on my box, that gives the expected result of 1
. Compiling without that option but with abs
declared as returning signed int
causes the program to print 2
.
(The real solution to this problem is to not use library identifiers for your own functions. Also note that you shouldn't be printing an unsigned int
with %d
.)