Domanda

I've inherited some code (from someone who has left) and found this little snippet:

double minX = xVal.find('.') == string::npos ? (double)atoi(xVal.c_str()) : atof(xVal.c_str());
double minY = yVal.find('.') == string::npos ? (double)atoi(yVal.c_str()) : atof(yVal.c_str());

Is there some reason why he chose to use atoi for integer types? I can't see a problem with:

double minX = atof(xVal.c_str());
double minY = atof(yVal.c_str());

Thanks.

È stato utile?

Soluzione 2

No reason. These ternary operators are extra. But its better use strtod instead atof - atof does not detect overflow and underflow errors.

Altri suggerimenti

Really you shouldn't be using either atoi or atof. They're both deprecated have been replaced by strtol and strtof respectively.

His code was : double minX = (double)atoi(xVal.c_str());

Then he figured out that float exists and adapted the code without thinking.

Possibly he was mislead by the name atof and he forgot that it returns a double rather than a float. If atof returned a float, then there could be some loss of precision for integer values. For example, on my computer:

char buffer[20];
itoa(INT_MAX-113, buffer, 10);
double minXF = (float)atof(buffer);
double minXI = (double)atoi(buffer);    
std::cout << (int)minXF << std::endl;
std::cout << (int)minXI << std::endl;   

Returns:

2147483520
2147483534

However, since atof returns a double, that is all irrelevant and there is no real reason to use atoi. So, use the safe equivalents as per the other answers and possibly interrogate the original author about it if you happen to see him out to dinner.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top