Reputation: 74
I am testing function 'min', which returns smaller of two double
values, in own driver.
Output should be as follows:
Please enter FIRST double value:
...
Please enter SECOND double value:
...
but I receive preceding messages in reverse order. What is the correct explanation for this issue?
Here is the full code:
#include <stdio.h>
#include <stdbool.h>
double min(double x, double y) { return x < y ? x : y; }
void set_response(bool *);
double get_double(int);
int main(void)
{
bool quit = false;
printf("-----This is the driver for evaluation of \'min\' function.-----\n");
printf("-----Enter string not beginning with \'q\' to continue.____-----\n");
printf("-----Enter string beginning with \'q\' to quit.____________-----\n");
while (set_response(&quit), !quit)
printf("Result of \'min\' function is: %f\n", min(get_double(1), get_double(2))), getchar();
printf("Thanks for efforts, dude!\n");
return 0;
}
void set_response(bool * resp)
{
if (getchar() == 'q')
*resp = true;
else
*resp = false, scanf("%*s");
}
double get_double(int order)
{
printf("Please enter %s double value:\n", order == 1 ? "FIRST" : "SECOND");
double val;
while (scanf("%lf", &val) != 1)
{
scanf("%*s");
printf("Please enter %s correct double value:\n", order == 1 ? "FIRST" : "SECOND");
}
return val;
}
Upvotes: 1
Views: 72
Reputation: 14141
min(get_double(1), get_double(2))
is a function call, so the order of evaluation of its parameters is not guaranteed to be first get_double(1)
and second get_double(2)
An workaround may be:
double x1 = get_double(1);
double x2 = get_double(2);
and then use x1 and x2 as parameters in the function call:
min(x1, x2)
Upvotes: 3
Reputation: 16540
follow the axiom:
*only one statement per line and (at most) one variable declaration per statement.*
the order of the parameter evaluation in this line:
printf("Result of \'min\' function is: %f\n", min(get_double(1), get_double(2)));
getchar();
is from right to left because the parameters are pushed onto the stack from right to left.
Strongly suggest removing all the 'clever' (but does not work as expected) stuff from your code.
In this case, do the two calls to get_double()
and save the results, then call the printf()
function.
Upvotes: 0