Search code examples
cglibcatoi

Different results when using atoi() for C in Mac OS X and Ubuntu


Here's the code which I ran on Mac OS X (10.8.1, 64-bit and 10.6.8, 32-bit) and Ubuntu (10.04, 32-bit):

printf("%d\n", atoi("2147483648"));
// returns -2147483648 in Mac OS X 10.8.1 and 10.6.8
// returns 2147483647 in Ubuntu

Here's what I found after some Googling: http://gynvael.coldwind.pl/?id=365

Is there any reason why the output varies on different systems?


Solution

  • This is not surprising, because the behavior is not specified by the standard:

    There is no standard specification on what happens when the converted value would be out of the range of representable values by an int.

    The strtol function gives you more info in the return, as it sets errno to ERANGE when the value does not fit in a long int.