1

I am complete new to c programming. i ran this code to try to understand the order of precedence in c programming-

#include <stdio.h>

int main()
{
    float sum = 8 / 4 * 2;

    printf("\n the solution of the expression is  %f", sum);
    return 0;
}

for this code i am correcly getting the output 4.000000

however if i write the print statement as

printf("\n the solution of the expression is  %f", 8 / 4 * 2);

i am getting the output as 0.000000. can anyone tell why does it give me different output for the same expression?

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621

1 Answers1

4

The expression 8 / 4 * 2 is an integer operation with an integer result.

The variable sum if a float variable, so its value will be a floating point value, which can be used together with the %f format specifier.

But when you use the expression directly in printf you attempt to print an int value using the mismatching %f specifier, which leads to undefined behavior.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621