switch case error

G

gouqizi.lvcha

Hi, All:

I remembered that I met a compiler error before that says something
like "cannot declare variable past a label", who know exectly of what
the error is?

For example:

int c;
switch (c)
case 1:

....
break;

case 2:
int x;
break;


Thanks

rick
 
D

davidrubin

Hi, All:

I remembered that I met a compiler error before that says something
like "cannot declare variable past a label", who know exectly of what
the error is?

For example:

int c;
switch (c)
case 1:

....
break;

case 2: {
int x; }
break;

Introduce a new scope. /david
 
V

Victor Bazarov

I remembered that I met a compiler error before that says something
like "cannot declare variable past a label", who know exectly of what
the error is?

For example:

int c;

You forgot to initialise it or to assign anything to it...
switch (c)

{
case 1:

....
break;

case 2:
int x;
break;

case 3:
...

and at this point, should 'c' be 3, the declaration of 'x' is
bypassed by this case label. While 'x' should be visible, its
declaration/definition isn't "executed". That's what is not
allowed. To overcome it you need to surround the contents of
the 'case 2' block with curly braces thus making it a compound
statement:

case 2:
{
int x;
...
break;
}

V
 
G

gouqizi.lvcha

Victor,

"Some declaration is bypassed by some execution path" will cause what
problem? It is quite strange.

Rick
 
D

Dan Cernat

Victor,

"Some declaration is bypassed by some execution path" will cause what
problem? It is quite strange.

Rick

That is why that is an error. The problem isn't the fact that "some
declaration is bypassed by some execution path". The problem is that
the variable whos declaration was bypassed is visible down the
execution path.

#include <iostream>

int main()
{
int c = 0;

std::cin >> c;

switch(c)
{
case 1:
int x = 0;
++x;
break;
case 2:
++x; // <-- the problem is here
}

return 0;
}

the spot I marked is part of the scope of x. the problem is that if c
== 2, the declaration of x is never executed.

HTH
dan
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top