Answer to Quiz 10(a) Tue 30 Oct 2001
1. Consider the program below :
#include<stdio.h>
variables
void next ( char *p ); -------------------------
in main | in square
int main(void) =========================
{ before a |
char a = 'D'; +-----+ |
next(&a); | 'D' | |
putchar(a); +-----+ |
return 0; during |
} a | p n
+-----+ | +-----+ +-----+
void next ( char *p ) | 'D' | <---|- &a | | 'E' |
{ +-----+ | +-----+ +-----+
char n = (*p < 'Z'? ++*p : 'A'; |
*p = n; a |
} after +-----+ |
| 'E' | |
+-----+ |
Make at the right of the program a diagram of all variables in main
and next.
Illustrate what happens before, during, and after the
call of next(&a).
What does the program print? E
2. Suppose we wish to manage the score of a game with the
following function :
void score ( int *wins, int flag );
/* if flag = 0, then score adds *wins to the sum of wins;
if flag = 1, then on return, *wins contains the number of wins */
Give a definition of score. Make sure score ``remembers''
the number of wins.
void score ( int *wins, int flag )
{
static int cnt = 0;
if (flag == 0) cnt += *wins;
if (flag == 1) *wins = cnt;
}