0

I came across the following code and can't seem to understand what's going on here. The enum pattern is never changed so why do a switch on it?

enum pattern { PAT_ZERO, PAT_SEQ, PAT_PIPE };
static enum pattern pattern;

static ssize_t fill_in_buf(struct thread *ignore, void *buf, size_t nbytes)
{
    size_t i;
    __u8 *p;

    (void)ignore;

    switch (pattern) {
    case PAT_ZERO:
        printf("fill_in_buf PAT_ZERO\n");
        memset(buf, 0, nbytes);
        break;

    case PAT_SEQ:
        printf("fill_in_buf PAT_SEQ\n");
        for (p = buf, i = 0; i < nbytes; ++i, ++p)
            *p = i % 63;
        break;

    case PAT_PIPE:
        printf("fill_in_buf PAT_PIPE\n");
        return fread(buf, 1, nbytes, stdin);
    }

    return nbytes;
}
tzippy
  • 6,458
  • 30
  • 82
  • 151

1 Answers1

0

It looks like test/debugging code, the programmer wanted a few varieties to choose from.

It's quite unexpectedly written, typically you'd see this done with the preprocessor and #if defined to choose one code path.

The two first lines could be clarified to:

static const enum { PAT_ZERO, PAT_SEQ, PAT_PIPE } pattern = PAT_ZERO;

Since there's no point in introducing a name for the enum, or making the variable non-const.

unwind
  • 391,730
  • 64
  • 469
  • 606