D&C Lug - Home Page
Devon & Cornwall Linux Users' Group

[ Date Index ][ Thread Index ]
[ <= Previous by date / thread ] [ Next by date / thread => ]

[LUG] Sorted++ !



On Thu, 8 May 2003, Darke, Clive wrote:

> The problem here is scoping I think.  While it is perfectly legal to declare
> a new variable after executable code in C++ (unlike C earlier than C99) that
> is not the problem, it is the initialization.  In case 0, c is initialized;
> in case 1 it is not.  The key is that a case statement does not generate a
> block of scope automatically, you have to explicitly define one.  I think
> you probably meant:
>
> 	case 0 :
> 	{
> 	   int * c = new int;
> 	   // .... etc
> 	   break;        // can be inside or outside this block
> 	}
> 	case 1 :
> 	{
> 	   int * d = new int;
> 	   break;
> 	}
>
> ... and this is not because you are new to C++, I showed this to a couple of
> other wrinkly coders and they didn't see it either!
>
> Clive
> (wrinkly coder)
>
>
> -----Original Message-----
> From: Tom Glare [mailto:tom@xxxxxxxxxxxxxxxxxxxx]
> Sent: Wednesday, May 07, 2003 9:26 PM
> To: list@xxxxxxxxxxxx
> Subject: [LUG] A programming problem
>
>
> Are there any Charlie Double Plus programmers who could explain this
> little conundrum to me ?
>
> When I compile the following programme
>
> ===
>
> int main() {
>    int * a = new int;
>    int b;
>    switch (b) {
>       case 0 :
>          int * c = new int;
>          // int * c;                  Compiles sucessfully
>          // c = new int;              if I do it this way
>          break;
>       case 1 :
>          int * d = new int;
>          break;
>    }
>    return 0;
> }
> ===
> - I get the following error :
> ===
>
> test.cpp: In function `int main ()':
> test.cpp:10: jump to case label
> test.cpp:6:   crosses initialization of `int *c'
>
> ===
>
> Am relatively new to the wonderful world of C++, so is probably something
> elementary I am getting wrong.
>
>
Absolutely spot on !  Thanks very much.  Is not blindingly obvious why you
have to do this, but it does make sense if you think about the basic
scoping rules. Helps my simple brain if I envisage it as an alternative to
a series of if/else statements, where of course you would have the
squiggly brackets anyway.

Did a little research on the big wubble-u and it seems that this is now
the "correct" behaviour for the compiler - previous versions may have let
you "get away with it".

Cheers, Tom



--
The Mailing List for the Devon & Cornwall LUG
Mail majordomo@xxxxxxxxxxxx with "unsubscribe list" in the
message body to unsubscribe.


Lynx friendly