gyan wrote:
> follwing code gives error:
> 1 #include<iostream.h>
> 2 int main()
> 3 {
> 4 int a=5,b;
> 5 switch(a){
> 6 case 1:
> 7 {b=5;
> 8 break;
> 9 }
> 10 case 2:
> 11 b=7;
> 12 int c=4;
> 13 c=3;
> 14 break;
> 15 case 3:
> 16 c=2;
'c' is local to this 'switch'. However, if 'a' is 3, then the declaration
of 'c' (and its initialisation) does not get "executed". That's forbidden.
> 17 break;
> 18 }
> 19 return 0;
> 20 }
>
>
> "1.cpp", line 15: Error: This case bypasses initialization of a local
> variable.
>
> If i put statements under case 2: in {}, i get error:
> "1.cpp", line 18: Error: c is not defined.
>
> So exactly what is happening?
What's happening is simple: you're trying to declare/define/initialise
a variable in one place and use it later, but the control flow _allows_
the delcaration/definition/initialisation to be skipped. Similar to
goto blah;
int c = 5; // this is skipped by the goto.
blah:
c = 2;
> i have read that
> A problem occurs , when a variable is declared AND INITIALIZED, in a
> location where the flow-of-control is undetermined relative to the
> location of the declaration (after the declaration has been moved to
> the beginning of the scope block).
I am not sure I understand that (my coffee hasn't kicked in yet).
> Or perhaps a better way of saying it, is the compiler recognizes the
> declaration and initialization as two different things:
>
> the declaration is moved to a "static" location at the beginning of
> the scope block
> while the initialization is really an assignment statement whose
> execution is "dynamic", that is, it depends on the flow of control
> through the program
>
>
> Can someone one explain reason in a more common way. I am not able to
> understand it.Can you put code, as seen by compiler.
The relevant part of your switch statement is semantically equivalent
to this:
if (a == 3) goto case3;
case2:
int c = 4;
c = 3;
case3:
c = 2;
If 'a' is indeed 3, the code that declares/defines/initialises 'c' is
stepped over.
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
|