I have a function in C that compiles fine until I add another case to my switch statement and declare a variable.
Here's the function
void evaluate(int num_inputs) {
struct gate *ptr = gatehead;
while (ptr->next != NULL) {
switch (ptr->kind) {
case 0:
if (get_input_value(ptr->params[0]) && get_input_value(ptr->params[1])) {
write_to_output(true, ptr->output);
} else {
write_to_output(false, ptr->output);
}
break;
case 1:
if (get_input_value(ptr->params[0]) || get_input_value(ptr->params[1])) {
write_to_output(true, ptr->output);
} else {
write_to_output(false, ptr->output);
}
break;
case 2:
if (!(get_input_value(ptr->params[0]) && get_input_value(ptr->params[1]))) {
write_to_output(true, ptr->output);
} else {
write_to_output(false, ptr->output);
}
break;
case 3:
if (!(get_input_value(ptr->params[0])) && !(get_input_value(ptr->params[1]))) {
write_to_output(true, ptr->output);
} else {
write_to_output(false, ptr->output);
}
break;
case 4:
if ((get_input_value(ptr->params[0]) || get_input_value(ptr->params[1])) && !(get_input_value(ptr->params[0]) && get_input_value(ptr->params[1]))) {
write_to_output(true, ptr->output);
} else {
write_to_output(false, ptr->output);
}
break;
case 5:
if (get_input_value(ptr->params[0])) {
write_to_output(false, ptr->output);
} else {
write_to_output(true, ptr->output);
}
break;
case 6:
if (get_input_value(ptr->params[0])) {
write_to_output(true, ptr->output);
} else {
write_to_output(false, ptr->output);
}
break;
case 7:
char* d = "DECODER";
printf("%s", d);
break;
}
ptr = ptr->next;
}
}
If I comment out case 7, everything works fine. Even keeping the print and break compiles, but declaring the char* causes the error "expected expression"
CodePudding user response:
The problem is that the case 7:
label is immediately followed by a variable declaration.
case 7:
char* d = "DECODER";
A label can only be applied to a statement, and a declaration is not considered a statement. You can get around this by adding an empty statement before the case label:
case 7:
;
char* d = "DECODER";