The following C++ program calls strtoul
of negative 1. Since no negative numbers are representable in any unsigned type, I had expected this to fail and return 0
If no valid conversion could be performed, a zero value is returned.
but instead a large positive number is returned
If the value read is out of the range of representable values by an unsigned long int, the function returns
ULONG_MAX
(defined in<climits>
), anderrno
is set toERANGE
.
#include <cstdlib>
#include <iostream>
int main () {
{char s[] = "-1";
for (int b=0; b<17; ++b)
std::cout << "strtoul (unsigned) of " << s
<< " with base arg " << b
<< ": " << strtoul(s,0,b) << std::endl;}
}
Why does strtoul not fail and return 0 for negative numbers?
If the value is negative, the strtol() function will return LONG_MIN, and the strtoll() function will return LONGLONG_MIN. If no characters are converted, the strtoll() and strtol() functions will set errno to EINVAL and 0 is returned.
A negative number is a number whose value is always less than zero and it has a minus (-) sign before it. On a number line, negative numbers are represented on the left side of zero. For example, -6 and -15 are negative numbers.
Negative Numbers The simplest is to simply use the leftmost digit of the number as a special value to represent the sign of the number: 0 = positive, 1 = negative. For example, a value of positive 12 (decimal) would be written as 01100 in binary, but negative 12 (decimal) would be written as 11100.
Negative numbers can be thought of as resulting from the subtraction of a larger number from a smaller. For example, negative three is the result of subtracting three from zero: 0 − 3 = −3.
You better use cppreference.com for documentation it seems to be much more accurate:
if the minus sign was part of the input sequence, the numeric value calculated from the sequence of digits is negated as if by unary minus in the result type, which applies unsigned integer wraparound rules.
and as mentioned there optional plus or minus sign is a valid symbol
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With