Search code examples
ctype-conversionatoi

Is atoi() part of C standard?


Is atoi() part of C standard?

What should I use to convert char* to int if atoi() isn't standardised?


Solution

  • Yes, atoi() is part of standard C -- unfortunately.

    I say "unfortunately" because it does no error checking; if it returns 0, you can't tell whether it's because you passed it "0" or because you passed it "hello, world\n" (which has may have undefined behavior, but typically returns 0).

    The strtol() function is more complicated to use, but it does proper error checking. It returns a long result, which you can then convert to int -- ideally after checking that it's in the range INT_MIN to INT_MAX.

    Reference: N1570 7.22.1.2.