I used to teach C programming. This is the first question from the first test I ever gave.
The idea was simple: I wanted to see if the students knew the difference between an automatic variable:
16 int i = 0;
and a static one:
26 static int i = 0;
However, after the test I was forced to make an embarrassing admission: If I had taken my own test, I would have missed this question. So I had to get up in front of everybody and tell them, "There are two ways of getting full credit for problem #1. The first way is to give the correct answer; the other way is to give the answer I thought was correct.
So what's the correct answer?
1 /***********************************************
2 * Test question: *
3 * What does the following program print? *
4 * *
5 * Note: The question is designed to tell if *
6 * the student knows the difference between *
7 * automatic and static variables. *
8 ***********************************************/
9 #include <stdio.h>
10 /***********************************************
11 * first -- Demonstration of automatic *
12 * variables. *
13 ***********************************************/
14 int first(void)
15 {
16 int i = 0; // Demonstration variable
17
18 return (i++);
19 }
20 /***********************************************
21 * second -- Demonstration of a static *
22 * variable. *
23 ***********************************************/
24 int second(void)
25 {
26 static int i = 0; // Demonstration variable
27
28 return (i++);
29 }
30
31 int main()
32 {
33 int counter; // Call counter
34
35 for (counter = 0; counter < 3; counter++)
36 printf("First %d\n", first());
37
38 for (counter = 0; counter < 3; counter++)
39 printf("Second %d\n", second());
40
41 return (o);
42 }
(Next Hint 139. Answer 102.)