I'm fairly new to C and I have a small function which reads an input of a simple math operation (+,-,*,/) and then calculates the result accordingly and returns -nan if the input is incorrect.
float simple_math(void) {
float a, b;
int char_c;
int ret_a;
ret_a = scanf("%f %c %f", &a, &char_c, &b);
float result;
if (char_c == '+')
result = a + b;
else if (char_c == '-')
result = a - b;
else if (char_c == '*')
result = a * b;
else if (char_c == '/')
result = a / b;
else
result = 0.0 / 0.0;
return result;
}
This code works just fine. However, if I change the order of the first two lines the return value is -nan.
int char_c;
float a, b; // this was originally the first line
int ret_a;
Why does the order of the variable declarations matter?
int char_c;
should be
char char_c;
%c
is used to scan character and not int
so your scanf will lead to undefined behavior.
The side effect of undefined behavior is sometimes things work as expected. So please get rid of undefined behavior it has nothing to do with the ordering of variable definitions.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments