The first sum: 6.500000 The second sum: 4.500000 The third sum: 5.000000
Here is the program, again:
#include <stdio.h> /* Puzzle E14 -- assignment */ int main() { int a = 3; double b = 1.5; double sum; sum = a+b+2.0; printf("The first sum: %f\n", sum ); printf("The second sum: %f\n", sum = a+b ); sum = sum+0.5; printf("The third sum: %f\n", sum ); return 0; }
Examine this statement:
sum = a+b+2.0;
The assignment operator =
and the variable sum
are part of an expression.
The assignment operator has low precedence, so it is performed last.
It saves the value of the subexpression a+b+2.0
in the variable sum
.
The entire assignment expression has a value and a type, which is the value and type stored in the variable.
Another expression is part of the second printf
:
sum = a+b
It computes a value a+b
, stores that value in sum
.
The value of the entire expression is
a parameter to the printf
The entire assignment expression has a value and a type, the same as the value stored in the variable.
That is the value that the printf
uses.
printf("The second sum: %f\n", sum = a+b );
The third expression is:
sum = sum+0.5
This adds 0.5
to the value currently in sum
and puts the result back into sum
.
The second printf
works, but is best avoided since the code is unclear.