I've made the following MRE to represent the problem:
typedef struct {
char data[64];
} Message;
int main()
{
int type = 1;
switch (type)
{
case 1:
Message m = { "hello world" };
printf("%s\n", m.data);
break;
default:
break;
}
return 0;
}
The IDE underlines Message
in red and displays an error "Error (active) E1072: a declaration cannot have a label", but the build succeeds and the program runs. Why is that and/or how can I solve the error?
I'm using Microsoft Visual Studio Community 2022 (64-bit), version 17.9.1
As suggested by Ted Lyngmo in the comments section, the simplest solution is to surround switch
declarations with curly brackets:
switch (type)
{
case 1:
{
Message m = { "hello world" };
printf("%s\n", m.data);
break;
}
default:
break;
}