我可以假设 atoi() 出错时的行为是什么?

What can I assume about the behaviour of atoi() on error?

标准 C 库函数 atoi 在 ISO 9899:2011 中记录为:

7.22.1 Numeric conversion functions

1 The functions atof, atoi, atol, and atoll need not affect the value of the integer expression errno on an error. If the value of the result cannot be represented, the behavior is undefined.

...

7.22.1.2 The atoi, atol, and atoll functions

Synopsis

#include <stdlib.h>
int atoi(const char *nptr);
long int atol(const char *nptr);
long long int atoll(const char *nptr);

Description

2 The atoi, atol, and atoll functions convert the initial portion of the string pointed to by nptr to int, long int, and long long int representation, respectively. Except for the behavior on error, they are equivalent to

atoi: (int)strtol(nptr, (char **)NULL, 10)
atol: strtol(nptr, (char **)NULL, 10)
atoll: strtoll(nptr, (char **)NULL, 10)

Returns

3 The atoi, atol, and atoll functions return the converted value.

nptr 指向的字符串无法解析为整数时,预期的行为是什么?似乎存在以下四种意见:

以下哪种解释是正确的?请尽量参考权威文档

What is the intended behaviour when string pointed to by nptr cannot be parsed as an integer?

明确地说,这个问题适用于

// Case 1
value = atoi("");
value = atoi("  ");
value = atoi("wxyz");

而不是以下内容:

// Case 2
// NULL does not point to a string
value = atoi(NULL);
// Convert the initial portion, yet has following junk
value = atoi("123xyz");
value = atoi("123 ");

和 maybe/maybe 不是以下取决于 integer.

的用法
// Case 3
// Can be parsed as an _integer_, yet overflows an `int`.
value = atoi("12345678901234567890123456789012345678901234567890");

ato*() 的 "non-Case 2" 行为取决于

error 的含义

The atoi, atol, and atoll functions convert the initial portion of the string pointed to by nptr to int, long int, and long long int representation, respectively. Except for the behavior on error, they are equivalent to
atoi: (int)strtol(nptr, (char **)NULL, 10)
...
C11dr §7.22.1.2 2


当然 错误 包括情况 3:"If the correct value is outside the range of representable values"。 strto*(),虽然可能不是 ato*(),但在这种情况下确实设置了 <errno.h> 中定义的 错误 数字 errrno。由于 ato*() 的规范不适用于此 错误 ,溢出,结果是 UB per

Undefined behavior is otherwise indicated in this International Standard by the words ‘‘undefined behavior’’ or by the omission of any explicit definition of behavior. C11dr §4 2


对于情况 1,strto*() 的行为定义明确,未指定影响 errno。规范详细介绍了 (§7.22.1.4 4) 并将这些称为 "no conversion",而不是 error。因此它可以断言案例 1 strto*() 行为不是 错误 ,而是 "no conversion"。因此每 ...

"If no conversion could be performed, zero is returned. C11dr §7.22.1.4 8

...atoi("") 必须 return 0.