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
fail()
bit raised) with clang++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.
This has been discussed before here: Negative numeric string (e.g. "-10") to unsigned short
The answer is that according to the C++ standard 22.4.2.1.2p3, the conversion is required to fail and the value stores should be:
the most negative representable value or 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.
Therefore, clang++ is the correct behavior.
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