Trace a struct whose function pointer member switches itself

A sensor driver stores its current behaviour as a function pointer inside a struct. Each behaviour updates the level and may replace itself with the other behaviour for the next call. The program below calls m->step(m) six times.


C
struct meter;
void fast(struct meter *m);
void slow(struct meter *m);

struct meter {
    int level;
    void (*step)(struct meter *);
};

void fast(struct meter *m)
{
    m->level += 3;
    if (m->level >= 7)
        m->step = slow;
}

void slow(struct meter *m)
{
    m->level -= 1;
    if (m->level == 5)
        m->step = fast;
}

int main(void)
{
    struct meter m[1] = { { 1, fast } };
    for (int k = 1; k != 7; k++)
        m->step(m);
    return 0;
}


For each call, enter the name of the function that runs (fast or slow), the value of level after that call returns, and the name of the function that step points to after the call. Enter integers for the level.

CallFunction runLevel after callstep after call
1
2
3
4
5
6

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

More Function Pointers Questions: