Reputation: 93
I have a function to check if a string is a valid unsigned int
:
unsigned long int getNum(std::string s, int base)
{
unsigned int n;
try
{
n = std::stoul(s, nullptr, base);
std::cout << errno << '\n';
if (errno != 0)
{
std::cout << "ERROR" << '\n';
}
}
catch (std::exception & e)
{
throw std::invalid_argument("Value is too big");
}
return n;
}
However when I enter a value such as 0xfffffffff
(9 f's), errno
is still 0 (and no exception is thrown). Why is this the case?
Upvotes: 7
Views: 8474
Reputation: 26800
Let's see what happens when you assign 0xfffffffff
(9 f's) to an unsigned int
on an 64-bit machine.
#include <iostream>
int main(){
unsigned int n = 0xfffffffff; //decimal value 68719476735
std::cout << n << '\n';
}
The implicit conversion will result in a warning by the compiler but will not cause an exception.
The result type of stoul
is unsigned long
which on 64-bit machine is big enough to hold 0xfffffffff
, so there will be no exception.
Upvotes: 6