问题描述:

So, I have this function, and I am getting some really weird errors that I can't figure out.

void serialize_helper(huff *h, bits *history, char** a)

{

switch (h->tag) {

case LEAF:

char letter = h->h.leaf.c;

int arraynum = (int)letter;

a[arraynum] = bits_show(history);

putchar('\n');

return;

case NODE:

/* traverse left subtree */

bits_putlast('0',history);

serialize_helper(h->h.node.lsub,history, a);

bits_remove_last(history);

/* traverse right subtree */

bits_putlast('1',history);

serialize_helper(h->h.node.rsub,history, a);

bits_remove_last(history);

return;

default:

fprintf(stderr,"main.serialize_helper: bad tag\n");

exit(1);

}

}

I am getting this error for a simple variable definition (from char letter = ...;):

"huffenc.c:18: error: expected expression before ‘char’"

Furthermore, the compiler is acting like my declaration of "letter" does not exist:

"huffenc.c:19: error: ‘letter’ undeclared (first use in this function)"

网友答案:

If you want to define a variable in a switch directly after a case you need to have a block, e.g.

  case LEAF: {
    char letter = h->h.leaf.c;
    int arraynum = (int)letter;
    a[arraynum] = bits_show(history);
    putchar('\n');
    return;
  }

EDIT: The reason is simply that a label can only be followed by a statement, and a declaration or initialisation isn't a statement, while a block (i.e. compound statement) is.

相关阅读:
Top