Question 1 — Trace the assignments
Run the following program in your head first, then pick the answer.
#include<stdio.h>
int main(void){
int a, b;
a = 10;
b = 30;
b = a;
a = 5;
printf("a is %d, b is %d \n", a, b);
return 0;
}
What does this print?
a is 10, b is 30
a is 5, b is 10
a is 5, b is 30
a is 10, b is 10
Explanation: Trace the assignments one by one...
(1) a=10 → a:10
(2) b=30 → b:30
(3) b=a → b receives the value of a (10) → b:10 (30 is overwritten)
(4) a=5 → a is overwritten with 5 → a:5
∴ a is 5, b is 10
Question 2 — What if you use %f for an int?
The same program as Question 1, but printf's %d has been changed to %f.
int a, b;
a = 10; b = 30; b = a; a = 5;
printf("a is %f, b is %f \n", a, b); // changed to %f!
What does this print?
a is 5.000000, b is 10.000000
a is 0.000000, b is 0.000000 (or similar garbage)
Compile error
Explanation: Using %f (for floating-point) on an int does not produce the correct value.
The exact output depends on the platform, but expect 0.000000 or some meaningless number.
Use %d for int and %f for double!
Question 3 — What if you use %d for a double?
double a, b;
a = 3.1; b = 2.6; b = 2.12; a = 4.52;
printf("a is %f, b is %d \n", a, b); // only b uses %d!
What does this print?
a is 4.520000, b is 2.120000
a is 4.520000, b is 2
a is 4.520000, b is (garbage value)
Explanation: a is printed correctly as 4.520000 with %f, but b is a double printed with %d (for int), so it won't display correctly.
On some platforms you might see something like -488420520.
Always use %f for double values.