on the one hand, i like the compactness of Sinkula's code (i sometimes code like that), but on the other hand, it doesnt lend itself very well to readability for people not used to the style
int mygetd(double *result)
{
char buff [ 32 ]; /* modify as needed */
return fgets(buff, sizeof buff, stdin) && sscanf(buff, "%lf", result) == 1;
}
It might help you if we break out the "return" statement a little bit for readability.
So here is an example of his code broken out to an extreme degree. I normally wouldn't write such tedious code for a simple function, but this might make it more clear as to what the operations grouped in his "return" statement are actually doing.
int mygetd(double *result)
{
char buff [ 32 ]; /* modify as needed */
numBytesRead = 0;
isValidValue = 0;
numBytesRead = fgets(buff, sizeof buff, stdin)
if (numBytesRead>0) // format value, pass back as "result"
isValidValue = sscanf(buff, "%lf", result);
if (isValidValue == 1)
return 1; // value entered is good
else
return 0; // no valid value found
}
To understand how his combined return statement works, you can follow it by the C operators' order of precedence...
first the "fgets()" function is performed, if it evaluates as TRUE, then the "scanf(...) ==1" function is subsequently evaluated (note, the == 1 is redundant). if it also evaluates as TRUE, the entire function returns TRUE (1), and the variable "result" is passed back with correct value.
But if the "fgets()" function evaluates as false, the entire routine immediately returns with FALSE (0) and the "scanf()" function is not even performed, so the variable "result" is left unmodified.
Or if "scanf()==1" evaluates as false, the entire routine likewise returns FALSE and "result" is either unmodified or undefined (i forget which).
.