| View previous topic :: View next topic |
| Author |
Message |
gouqizi.lvcha@gmail.com Guest
|
Posted: Fri Sep 30, 2005 2:54 am Post subject: switch case error |
|
|
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
|
|
| Back to top |
|
 |
davidrubin@warpmail.net Guest
|
Posted: Fri Sep 30, 2005 3:17 am Post subject: Re: switch case error |
|
|
[email]gouqizi.lvcha (AT) gmail (DOT) com[/email] wrote:
| Quote: | 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
|
|
| Back to top |
|
 |
Victor Bazarov Guest
|
Posted: Fri Sep 30, 2005 3:20 am Post subject: Re: switch case error |
|
|
[email]gouqizi.lvcha (AT) gmail (DOT) com[/email] wrote:
| Quote: | 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...
{
| Quote: | 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
|
|
| Back to top |
|
 |
gouqizi.lvcha@gmail.com Guest
|
Posted: Fri Sep 30, 2005 12:31 pm Post subject: Re: switch case error |
|
|
Victor,
"Some declaration is bypassed by some execution path" will cause what
problem? It is quite strange.
Rick
|
|
| Back to top |
|
 |
Dan Cernat Guest
|
Posted: Fri Sep 30, 2005 12:47 pm Post subject: Re: switch case error |
|
|
[email]gouqizi.lvcha (AT) gmail (DOT) com[/email] wrote:
| Quote: | 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
|
|
| Back to top |
|
 |
gouqizi.lvcha@gmail.com Guest
|
Posted: Sat Oct 01, 2005 5:34 pm Post subject: Re: switch case error |
|
|
Thanks. I got it.
Rick.
|
|
| Back to top |
|
 |
|