473,748 Members | 3,697 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

variable declaration inside switch case label

Consider the following program:

#include <iostream>

using namespace std;

int main()
{
int i;

cin >i;

switch ( i )
{
case 1:
int case_1 = 1;
cout << "case_1 " << case_1 << endl;
break;
case 2:
int case_2 = 2;
cout << "case_2 " << case_2 << endl;
break;
}

return 0;
}

If a variable is declared inside any case label except the last case
label, I am getting compilation error. In this program I am getting
compilation error for the declaration

int case_1 = 1;

inside case 1.

But there is no compilation error for the declaration

int case_2 = 2;

inside case 2.

Kindly explain what is the difference and why is the declaration not
allowed in other case labels but allowed in the last case label in a
switch ?

Jun 17 '07 #1
14 13058
On Jun 17, 10:23 am, "subramanian10. ..@yahoo.com, India"
<subramanian10. ..@yahoo.comwro te:

If a variable is declared inside any case label except the last case
label, I am getting compilation error. In this program I am getting
compilation error for the declaration

int case_1 = 1;

inside case 1.

But there is no compilation error for the declaration

int case_2 = 2;

inside case 2.

Kindly explain what is the difference and why is the declaration not
allowed in other case labels but allowed in the last case label in a
switch ?
It's been a long, long time since I programmed and I'm starting to
pick it back up, so bear with me if I'm wrong:

The fact that erroring out on the first case statement and not on the
second leads me to believe it's not reporting the error on case_2
because it's not processing anymore after case_1, because it's already
in error. Have you tried removing the int case_1 = 1 to see if it
errs on the case_2 = 2 line?

Jun 17 '07 #2
su************* *@yahoo.com, India wrote:
Consider the following program:

#include <iostream>

using namespace std;

int main()
{
int i;

cin >i;

switch ( i )
{
case 1:
int case_1 = 1;
cout << "case_1 " << case_1 << endl;
break;
case 2:
int case_2 = 2;
cout << "case_2 " << case_2 << endl;
break;
}

return 0;
}

If a variable is declared inside any case label except the last case
label, I am getting compilation error. In this program I am getting
compilation error for the declaration

int case_1 = 1;

inside case 1.

But there is no compilation error for the declaration

int case_2 = 2;

inside case 2.

Kindly explain what is the difference and why is the declaration not
allowed in other case labels but allowed in the last case label in a
switch ?
Because it's a rule of C++ that a jump cannot pass over a variable
declaration in the same scope. So when you jump to case 2, you pass over
the variable declaration in case 1. But the variable declaration in the
last case is OK, because it is never jumped over.

The reason for the rule is that if you allowed a jump over a variable
declaration it would be very hard for the compiler to work out whether
to call a destructor for that variable. If you had jumped over the
variable declaration you would not need to call the destructor, if you
had not jumped then you would.

If you want to decalre variable inside switch statements, do it like this

switch ( i )
{
case 1:
{
int case_1 = 1;
cout << "case_1 " << case_1 << endl;
}
break;
case 2:
{
int case_2 = 2;
cout << "case_2 " << case_2 << endl;
}
break;
}

The extra { and } mean that the compiler has no trouble working out when
to call destructors.

Of there are no ddestructors for int variables, but there could be for
other variable types, and it was decided to made all variables the same
for this rule.

john
Jun 17 '07 #3
On Jun 17, 10:56 am, John Harrison <john_androni.. .@hotmail.com>
wrote:
subramanian10.. .@yahoo.com, India wrote:
Consider the following program:
#include <iostream>
using namespace std;
int main()
{
int i;
cin >i;
switch ( i )
{
case 1:
int case_1 = 1;
cout << "case_1 " << case_1 << endl;
break;
case 2:
int case_2 = 2;
cout << "case_2 " << case_2 << endl;
break;
}
return 0;
}
If a variable is declared inside any case label except the last case
label, I am getting compilation error. In this program I am getting
compilation error for the declaration
int case_1 = 1;
inside case 1.
But there is no compilation error for the declaration
int case_2 = 2;
inside case 2.
Kindly explain what is the difference and why is the declaration not
allowed in other case labels but allowed in the last case label in a
switch ?

Because it's a rule of C++ that a jump cannot pass over a variable
declaration in the same scope. So when you jump to case 2, you pass over
the variable declaration in case 1. But the variable declaration in the
last case is OK, because it is never jumped over.

The reason for the rule is that if you allowed a jump over a variable
declaration it would be very hard for the compiler to work out whether
to call a destructor for that variable. If you had jumped over the
variable declaration you would not need to call the destructor, if you
had not jumped then you would.

If you want to decalre variable inside switch statements, do it like this

switch ( i )
{
case 1:
{
int case_1 = 1;
cout << "case_1 " << case_1 << endl;
}
break;
case 2:
{
int case_2 = 2;
cout << "case_2 " << case_2 << endl;
}
break;
}

The extra { and } mean that the compiler has no trouble working out when
to call destructors.

Of there are no ddestructors for int variables, but there could be for
other variable types, and it was decided to made all variables the same
for this rule.

john
John - Thanks for good information. Is this documented somewhere?

Bharath

Jun 17 '07 #4
>
John - Thanks for good information. Is this documented somewhere?

Bharath
Well it's documented in the C++ standard, section 6.7.3, but I guess any
good C++ book would cover this.

Looking at the standard though, there's an exception to this rule which
I wasn't aware of. If the variable is a POD type (int is a POD type for
instance) and if the declaration does not have an initialiser then you
are allowed to 'jump' the variable declartion. I.e. if you had written

switch ( i )
{
case 1:
int case_1;
case_1 = 1;
cout << "case_1 " << case_1 << endl;
break;
case 2:
int case_2;
case_2 = 2;
cout << "case_2 " << case_2 << endl;
break;
}

the code would been legal (assuming I'm reading this right). Not sure
what the rationale is for that.

john
Jun 17 '07 #5
John Harrison wrote:
>>
John - Thanks for good information. Is this documented somewhere?

Bharath

Well it's documented in the C++ standard, section 6.7.3, but I guess any
good C++ book would cover this.

Looking at the standard though, there's an exception to this rule which
I wasn't aware of. If the variable is a POD type (int is a POD type for
instance) and if the declaration does not have an initialiser then you
are allowed to 'jump' the variable declartion. I.e. if you had written

switch ( i )
{
case 1:
int case_1;
case_1 = 1;
cout << "case_1 " << case_1 << endl;
break;
case 2:
int case_2;
case_2 = 2;
cout << "case_2 " << case_2 << endl;
break;
}

the code would been legal (assuming I'm reading this right). Not sure
what the rationale is for that.
The issue is skipping the initialization of a variable. If there's no
initialization, then there's nothing to skip, so the jump is harmless.

--

-- Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com)
Author of "The Standard C++ Library Extensions: a Tutorial and
Reference." (www.petebecker.com/tr1book)
Jun 17 '07 #6
Pete Becker wrote:
John Harrison wrote:
>>>
John - Thanks for good information. Is this documented somewhere?

Bharath

Well it's documented in the C++ standard, section 6.7.3, but I guess
any good C++ book would cover this.

Looking at the standard though, there's an exception to this rule
which I wasn't aware of. If the variable is a POD type (int is a POD
type for instance) and if the declaration does not have an initialiser
then you are allowed to 'jump' the variable declartion. I.e. if you
had written

switch ( i )
{
case 1:
int case_1;
case_1 = 1;
cout << "case_1 " << case_1 << endl;
break;
case 2:
int case_2;
case_2 = 2;
cout << "case_2 " << case_2 << endl;
break;
}

the code would been legal (assuming I'm reading this right). Not sure
what the rationale is for that.

The issue is skipping the initialization of a variable. If there's no
initialization, then there's nothing to skip, so the jump is harmless.
I don't understand. For a POD type there doesn't seem to be any
difference between

T x = y;

and

T x;
x = y;

so why is there this situation where on is legal and the other isn't. If
the initialisation (in the first case) is harmful, why isn't the
assignment in the second case? Why ban the first case when the same
effect can be achieved by the second case?

john

Jun 17 '07 #7
John Harrison wrote:
>
I don't understand. For a POD type there doesn't seem to be any
difference between

T x = y;

and

T x;
x = y;

so why is there this situation where on is legal and the other isn't. If
the initialisation (in the first case) is harmful, why isn't the
assignment in the second case? Why ban the first case when the same
effect can be achieved by the second case?
How would you succinctly describe the second case in order to write a
rule prohibiting skipping it? The rule is simply that skipping
initializers isn't allowed.

--

-- Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com)
Author of "The Standard C++ Library Extensions: a Tutorial and
Reference." (www.petebecker.com/tr1book)
Jun 17 '07 #8
Pete Becker wrote:
John Harrison wrote:
>>
I don't understand. For a POD type there doesn't seem to be any
difference between

T x = y;

and

T x;
x = y;

so why is there this situation where on is legal and the other isn't.
If the initialisation (in the first case) is harmful, why isn't the
assignment in the second case? Why ban the first case when the same
effect can be achieved by the second case?

How would you succinctly describe the second case in order to write a
rule prohibiting skipping it? The rule is simply that skipping
initializers isn't allowed.
Well granted that would be difficult. But why not allow both cases? That
what I'm suggesting. In other words non-POD declarations cannot be
skipped, but POD ones can with or without initialiser. What would be the
harm?

john
Jun 17 '07 #9
On Jun 17, 8:11 pm, John Harrison <john_androni.. .@hotmail.comwr ote:
John - Thanks for good information. Is this documented somewhere?
Well it's documented in the C++ standard, section 6.7.3, but I guess any
good C++ book would cover this.
Looking at the standard though, there's an exception to this rule which
I wasn't aware of. If the variable is a POD type (int is a POD type for
instance) and if the declaration does not have an initialiser then you
are allowed to 'jump' the variable declartion. I.e. if you had written
switch ( i )
{
case 1:
int case_1;
case_1 = 1;
cout << "case_1 " << case_1 << endl;
break;
case 2:
int case_2;
case_2 = 2;
cout << "case_2 " << case_2 << endl;
break;
}
the code would been legal (assuming I'm reading this right). Not sure
what the rationale is for that.
The problem is that if i == 2, and you jump to case 2, case_1 is
in scope. If case_1 had an initializer (either explicit
initialization, or a non-trivial constructor), presumable any
use of it without initialization is an error. if it doesn't,
presumably, you've covered your bets otherwise.

I think someone mentionned destructors. In fact, it has nothing
to do with destructors; the destructor of both case_1 and case_2
will be called when they go out of scope, at the closing brace
of the switch. Again, presumably, if the object didn't have a
non-trivial constructor, and wasn't initialized, presumably,
calling the destructor on it is OK.

You gave the key to understanding the rules in your first
answer, indirectly. A switch (and the break in each of the
cases) has the semantics of a goto. The real rule is that you
are not allowed to jump over a non-trivial initialization (but
leaving scope by any means causes the destructors to be called).

--
James Kanze (Gabi Software) email: ja*********@gma il.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Jun 17 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

83
6514
by: Alexander Zatvornitskiy | last post by:
Hello All! I'am novice in python, and I find one very bad thing (from my point of view) in language. There is no keyword or syntax to declare variable, like 'var' in Pascal, or special syntax in C. It can cause very ugly errors,like this: epsilon=0 S=0 while epsilon<10: S=S+epsilon
3
3184
by: Anoop | last post by:
Hi guys i have a piece of code main() { switch(...) { case 1: {
5
10152
by: Neil Zanella | last post by:
Hello, Unlike in pre-C99 versions of C where variables can only be defined at the beginning of blocks, C99 allows variables to be defined in arbitrary places inside blocks. However, gcc 3.2.2 seems to reveal that there are still places where this is illegal. For instance, consider the following code snippet. int main(void) { int i = 0;
23
19202
by: Russ Chinoy | last post by:
Hi, This may be a totally newbie question, but I'm stumped. If I have a function such as: function DoSomething(strVarName) { ..... }
7
25149
by: gyan | last post by:
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 }
4
2719
by: Ray | last post by:
Hello, I think I've had JavaScript variable scope figured out, can you please see if I've got it correctly? * Variables can be local or global * When a variable is declared outside any function, it is global regardless of whether it's declared with or without "var" * When it is declared inside a function, if declared with "var", it's local, if not, it's global
26
10214
by: Alexander Korsunsky | last post by:
Hi! I have some code that looks similar to this: -------------------------------------------- char array = "abcdefghij"; for (int i = 0; i < 10; i++) {
11
1630
by: cmk128 | last post by:
Hi I am using gcc void peter(){ int x; LABEL1: int y; <--------------- Error } Why ? and how to fix it?
8
11150
by: Dom | last post by:
This is a little tricky, but I think the error I'm getting isn't valid. The compiler just doesn't know my logic. MyObject o; switch (IntVariable) { case 1: o = new MyObject() break;
0
8828
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9537
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9319
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9243
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
4599
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4869
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3309
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2780
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2213
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.