Em 29-12-2013 23:37, James Harkins escreveu: > On Dec 30, 2013 3:41 AM, "Miguel Negrão" > <miguel.negrao-lists@xxxxxxxxxxxxxxxxx > <mailto:miguel.negrao-lists@xxxxxxxxxxxxxxxxx>> wrote: >> I don't find that reasoning convicing at all. Some strings can't be >> parsed into integers so the function must have a mechanism for failing, >> it can throw an error or return a value which represents a failure (nil, >> Nothing, Failure("failure string") etc). > > That's reasonable, though there's room to disagree. Plus it would break > backward compatibility, so I'd say if we do anything like this, SC4 > would be the time. > >> How do you even distinguish a >> proper match "0".asInteger from a failure "".asInteger ? > > Well, I think the C/Java approach would be to validate the string before > calling the conversion function. > > I guess that's the disagreement: Should asInteger be a dumb conversion > method (as it is now), or should it be a smarter interpreter of a string > which may or may not spell out a base 10 integer? Your view suggests > that the former approach is either insufficient or maybe outright > invalid. If that's what you're saying (a guess on my part, could be > wrong), then I'd have to disagree to an extent. You can always compose a > smarter converter on top of the "dumb" atoi(), giving you the choice of > how to validate the input. > > I do agree that the Haskell approach seems an improvement. > > hjh > Hi James, It seems the primitive just calls atoi. I'm sure there are historical reasons why atoi works the way that it does (performance ?), but to me it just seems like a very unsafe function. strtol seems to be able to detect non-matching strings: http://www.lemoda.net/c/string-to-int/index.html . it's easy to find many warnings against using atoi out there: https://www.securecoding.cert.org/confluence/display/seccode/INT06-C.+Use+strtol%28%29+or+a+related+function+to+convert+a+string+token+to+an+integer Any reason not to use strtol and and fail the primitive in case of no match ? Also notice that atoi has this issue: "If the converted value would be out of the range of representable values by an int, it causes undefined behavior." * I also found an alternative using boost: http://www.boost.org/doc/libs/1_55_0/doc/html/boost_lexical_cast.html http://cboard.cprogramming.com/cplusplus-programming/93871-using-atoi-bad-practice.html #include <boost/lexical_cast.hpp> int main() { int param = -1; try { param = boost::lexical_cast<int>(argv[1]); } catch(const boost::bad_lexical_cast &) { std::cout << "err converting param to integer. exiting..." << endl; return EXIT_FAILURE; } } best, Miguel Negrão http://www.friendlyvirus.org/miguelnegrao
Attachment:
signature.asc
Description: OpenPGP digital signature