Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C vs C++ switch statement variable definition vs declaration

Tags:

I was playing with some syntax and found some strange compiler rules, was wondering what the reasoning is for this

C will not compile this but C++ will:

switch (argc) { case 0:     int foo;     break; default:     break; } 

Both C and C++ will compile this:

switch (argc) { case 0:     ; int foo;     break; default:     break; } 

C will compile this but not C++:

switch (argc) { case 0:     ; int foo = 0;     break; default:     break; } 

gcc -v is gcc version 4.9.3 (MacPorts gcc49 4.9.3_0) if it matters. I realize the solution is to wrap the contents of case 0: with curly brackets, but I am more interested in the reasoning for compilation errors

like image 375
asimes Avatar asked Jul 22 '15 04:07

asimes


People also ask

What is the difference between variable declaration and variable definition in C?

Declaration means that variable is only declared and memory is allocated, but no value is set. However, definition means the variables has been initialized.

Can you declare variables in a switch case C?

Do not declare variables inside a switch statement before the first case label. According to the C Standard, 6.8.

What is definition and declaration in C?

i.e., declaration gives details about the properties of a variable. Whereas, Definition of a variable says where the variable gets stored. i.e., memory for the variable is allocated during the definition of the variable. In C language definition and declaration for a variable takes place at the same time.

Can you declare variable inside switch statement?

Declaring a variable inside a switch block is fine. Declaring after a case guard is not.


1 Answers

case 0:     int foo; 

In both C and C++ a labeled statement is a label followed by a statement. However in C++ the definition of a statement includes "block declarations" (that is declarations and definitions that may appear in a block) whereas in C it does not (in C a block is a sequence of "block items", which are either block declarations or statements - in C++ it's a sequence of statements, which include block declarations).

case 0:     ; int foo; 

This works because ; is a(n empty) statement in both C and C++, so here we indeed have a label followed by a statement.

case 0:     ; int foo = 0; 

As was already explained in the comments, this does not work in C++ because C++ makes it illegal to jump over an initialization.

like image 61
sepp2k Avatar answered Oct 01 '22 15:10

sepp2k