I came across a difference in behavior, between gcc (4.9.2) and clang (3.5.0), which surprised me.
When I try to feed an unsigned int
from an std::istringstream
initialized with a negative value ("-15", in the example) I get
- an error (with
fail()
bit raised) with clang++ - the initialization with
signed(-15)
with gcc++
I prepared the trivial following example program.
#include <sstream>
#include <iostream>
int main ()
{
std::istringstream iss("-15");
unsigned int ui;
iss >> ui;
std::cout << "ui[" << ui << "] signed(ui)[" << signed(ui)
<< "] flags[" << iss.fail() << iss.good() << iss.bad()
<< iss.eof() << "]\n";
return 0;
}
With clang++, I obtain the following output
ui[0] signed(ui)[0] flags[1001]
With g++, I obtain the following output
ui[4294967281] signed(ui)[-15] flags[0001]
I have two questions.
The first is obvious: who's right? clang++, g++ or is an undefined behaviour?
The second is: how can I force the gcc++ to behave like the clang++, giving an error when extracting an unsigned value from a string beginning with a minus?
Thanks and sorry for my bad english.
EDIT 2016.04.03
I realized that this isn't a difference between g++ and clang++, but a difference between libstd++ and libc++.
Compiling and linking with clang++ and libstd++, I obtain the same output I get with g++.
Sorry.
gcc
/clang
are you using? I get the same result on Windows with g++ 5.1.0 and clang 3.7.0 (same as your g++ output). – Thrashstd::stroull
, which should behave as g++ did for you (but I found the C standard a bit fuzzy about this behavior... ). – Thrashstrtoull
negates its result in the return type . However the C++ standard also says that this extraction may yield "[...] zero for an unsigned integer type, if the field represents a value too large negative to be represented in val. ios_base::failbit is assigned to err." and it is not clear whether "represented in" an unsigned int also allows the usual signed-unsigned conversion. (But if it does then it is unclear in what situations this failure zero would be returned) – Tem-
take whatever error handling action; or if it is not-
then put it back and do the extraction – Tem