Even though the string conversion succeeds, testing errno
returns a value indicating an error:
#include <stdlib.h>
#include <sys/errno.h>
const char* numberString = "7";
char* endPtr;
errno = 0;
long number = strtol(numberString, &endPtr, 10);
NSLog(@"%ld", number);
if (errno) {
perror("string to integer conversion failed");
}
The output is (on the Simulator, iOS 7)
$ 2014-05-22 09:27:32.954 Test[2144:60b] 7
$ string to integer conversion failed: No such process
The behavior is similar on the device.
The man page for strtol
says in a comment:
RETURN VALUES
The strtol(), strtoll(), strtoimax(), and strtoq() functions return the result of the conversion, unless the value would underflow or overflow. If no conversion could be performed, 0 is returned and the global variable errno is set to EINVAL (the last feature is not portable across all platforms). If an overflow or underflow occurs, errno is set to ERANGE and the function return value is clamped according to the following table.
It's quite unclear what this exactly means for iOS. Any insights here?
Edit:
It turned out that the function call NSLog
did set errno
. So, @Mat in his answer and comments was spot on, saying that "all bets are off when testing errno
AFTER calling an unrelated function (here NSLog
).