Kal
Kal

Reputation: 1359

Why does std::stoul convert negative numbers?

As shown in http://ideone.com/RdINqa, std::stoul does not throw a std::out_of_range for negative numbers, but wraps them around. Why is this? Seems like -4 is out of the range of the type unsigned long so it should throw.

Upvotes: 19

Views: 4307

Answers (1)

Igor Tandetnik
Igor Tandetnik

Reputation: 52581

21.5 Numeric conversions

unsigned long stoul(const string& str, size_t *idx = 0, int base = 10);

Effects: ...call[s] strtoul(str.c_str(), ptr, base) ... returns the converted result, if any.

Throws: ...out_of_range if the converted value is outside the range of representable values for the return type.

"Converted value" here is the value returned by strtoul. Which, of course, is of type unsigned long and so can't be outside of the range of representable values for the return type of stoul, which is also unsigned long.

As far as I can tell, only stoi can throw out_of_range, because it returns int but uses strtol which returns long.

Further, the way C standard specifies strtoul, it is required to accept the string "-4" and return a value equal to -(unsigned long)4. Why it's specified this way, I don't know.

Upvotes: 16

Related Questions