Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

istream behavior change in C++ upon failure

Tags:

Take from: cppreference

Until C++11:

If extraction fails (e.g. if a letter was entered where a digit is expected), value is left unmodified and failbit is set.

Since C++11:

If extraction fails, zero is written to value and failbit is set. If extraction results in the value too large or too small to fit in value, std::numeric_limits<T>::max() or std::numeric_limits<T>::min() is written and failbit flag is set.

Due to this change, this means that the following snippet:

int x = 1; std::cin >> x; return x; 

in the event that the numerical conversion fails, will return 1 before C++11, and 0 otherwise.

Why would the standard committee introduce such a subtle breaking change? Or rather, what kind of code was possible prior to C++11 that warranted this change?

like image 808
Borgleader Avatar asked Oct 22 '13 15:10

Borgleader


1 Answers

It seems as originally specified, the operator>>s were broken in some cases (i.e. strictly speaking couldn't exist). This is the "fix".

In a draft from early 2011, The Standard is basically the same in this regard as it was in 2003. However, in a library defect report opened by Matt Austern (in 1998!), num_get<>::get() doesn't exist for short and int. So they were changed to use the long version, and check the read number falls within the correct range.

The defect report is here.

(Doesn't really explain why they didn't think they could keep the originally intended behaviour, but it is why this part of The Standard was changed.)

like image 179
BoBTFish Avatar answered Sep 17 '22 20:09

BoBTFish