|
||
Title: C++ problem Post by curt_cobain on Sep 28th, 2008, 1:06pm Following code will give error switch(i) { int x=10; case 1:cout<<"A"; } Following code will node give error switch(i) { int x; case 1:cout<<"A"; } Why?????// |
||
Title: Re: C++ problem Post by towr on Sep 28th, 2008, 1:16pm If I had to guess, I would say that declaring variables outside of cases is allowed (but probably a bad habit), whereas changing them isn't. |
||
Title: Re: C++ problem Post by 0.999... on Sep 28th, 2008, 2:13pm Also odd is the fact that I can easily undermine the system employed by simply doing this (which compiles in my GCC compiler): #include <iostream> using namespace std; int main() { int i = 6; switch(i) { int x; case 6: cout << "Hello world!" << endl; default: x = 1; } return 0; } |
||
Title: Re: C++ problem Post by towr on Sep 29th, 2008, 12:36am How is that undermining the system exactly? I can't see any reason why that shouldn't compile; and it's basically an example of Curt's second example which didn't give an error (although it'd be clearer if he had used "not" instead of "node" ;)). |
||
Title: Re: C++ problem Post by 0.999... on Sep 29th, 2008, 4:32pm Disregard that. This works: switch(i) { int x; x = 2; case 6: x = 1; cout << "Hello world!" << endl; } So, it appears that you can't declare and initialize a new variable in the same statement, but you can do anything else with it. Also interesting is that the following prints "Hello, world": switch(i) { i = 2; case 6: cout << "Hello world!" << endl; } Which means that the variable given to the switch is evaluated only once. I declared "i" as volatile to receive the same result. |
||
Title: Re: C++ problem Post by towr on Sep 30th, 2008, 1:13am on 09/29/08 at 16:32:05, 0.999... wrote:
|
||
Title: Re: C++ problem Post by SMQ on Sep 30th, 2008, 5:07am on 09/30/08 at 01:13:36, towr wrote:
Which is also why switch(foo) { int bar = 1; ... } is illegal: by the rules of the language the variable bar must be initialized, but it's in a location where the initialization code will never be executed -- a contradiction. --SMQ |
||
Powered by YaBB 1 Gold - SP 1.4! Forum software copyright © 2000-2004 Yet another Bulletin Board |