473,796 Members | 2,632 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Question on switch block scope

I was reading some text and I came across the following snippet

switch('5')
{
int x = 123;
case '5':
printf("The value of x %d\n", x);
break;
}
Now according to the text the memory would be allocated for the varible x but

the value of x would be an intermediate one. Can anybody expain the rationale

for this I ran this snippet [ with the obvious additions] through a C++

compiler and it gave me an error for this the following definition

int x = 123;

Is this sort of behavior of any use?

I could have better done through

{
int x = 123;
switch('5') {
....
}
}

But I was just wondering as to even declaring a variable in the switch level

scope should be allowed?

--
FUCK SCO!
Imanpreet Singh Arora
isingh AT acm DOT org
Even if you are on the right track you are going to get run over if you just
keep sitting there . - Will Rogers
Nov 13 '05 #1
18 3462
On Thu, 13 Nov 2003 12:26:59 -0800, Minti wrote:
I was reading some text and I came across the following snippet

switch('5')
{
int x = 123;
case '5':
printf("The value of x %d\n", x);
break;
}
Now according to the text the memory would be allocated for the varible x but
the value of x would be an intermediate one. Can anybody expain the rationale


The assignment of 123 to x never happens
The code is equivalent to:

goto foo;
{
int x = 123;
foo:
printf("The value of x %d\n", x);
}

-Sheldon

Nov 13 '05 #2
On Thu, 13 Nov 2003 16:20:04 -0500, Sheldon Simms
<sh**********@y ahoo.com> wrote:
On Thu, 13 Nov 2003 12:26:59 -0800, Minti wrote:
I was reading some text and I came across the following snippet

switch('5')
{
int x = 123;
case '5':
printf("The value of x %d\n", x);
break;
}
Now according to the text the memory would be allocated for the varible x but
the value of x would be an intermediate one. Can anybody expain the rationale


The assignment of 123 to x never happens
The code is equivalent to:

goto foo;
{
int x = 123;
foo:
printf("The value of x %d\n", x);
}

-Sheldon


Is this not a declaration with initialization, rather than an
assignment?

--
Al Balmer
Balmer Consulting
re************* ***********@att .net
Nov 13 '05 #3
Minti wrote [reformatted for better line length and spacing]:

I was reading some text and I came across the following snippet

switch('5')
{
int x = 123;
case '5':
printf("The value of x %d\n", x);
break;
}
Now according to the text the memory would be allocated for the varible x
but the value of x would be an intermediate one. Can anybody expain the
rationale for this
Which "this" do you mean? Why `x' is indeterminate,
or why the code was written this way?

The value of `x' is indeterminate because the `switch'
statement jumps directly to the selected `case' or `default'.
The executable code that sets `x' equal to 123 cannot be
reached, and thus is not executed.

The programmer's reason for attempting this construct
is a mystery I am unable to explain. Perhaps his or her
grasp of C was not very firm.
I could have better done through

{
int x = 123;
switch('5') {
....
}
}
That is fine; you have cured the indeterminacy.
But I was just wondering as to even declaring a variable in the switch
level scope should be allowed?
Variable declarations are permitted at the start of
*any* {}-enclosed executable block. There is nothing special
about `switch' in this regard.

Is the technique useful? Yes, it can be. If a block
is the only user of some particular variable, it may be
a good idea to limit the variable's scope to the block.
This can emphasize to the human reader that the variable
has no significance outside the block, and may also help
the compiler discover when the variable has "died" so it
can re-use the registers or other resources that held it.
FUCK SCO!


No; you might impregnate them and help them propagate
their genes. You are already known as someone who adds to
the load of mindless profanity under which we groan; do
you also want to become known as the father of little SCOlet?

--
Er*********@sun .com
Nov 13 '05 #4
On Thu, 13 Nov 2003 14:31:36 -0700, Alan Balmer wrote:
On Thu, 13 Nov 2003 16:20:04 -0500, Sheldon Simms
<sh**********@y ahoo.com> wrote:
On Thu, 13 Nov 2003 12:26:59 -0800, Minti wrote:
I was reading some text and I came across the following snippet

switch('5')
{
int x = 123;
case '5':
printf("The value of x %d\n", x);
break;
}
Now according to the text the memory would be allocated for the varible x but
the value of x would be an intermediate one. Can anybody expain the rationale


The assignment of 123 to x never happens
The code is equivalent to:

goto foo;
{
int x = 123;
foo:
printf("The value of x %d\n", x);
}

-Sheldon


Is this not a declaration with initialization, rather than an
assignment?


Well yes it is, but it doesn't make a difference.

6.8#3
The initializers of objects that have automatic storage duration, ...
are evaluated and the values are stored in the objects ... each time
the declaration is reached in the order of execution, as if it were a
statement

In the examples above, the declaration is never reached and so the
variable is not initialized.
Nov 13 '05 #5
On Thu, 13 Nov 2003 18:13:30 -0500, Sheldon Simms
<sh**********@y ahoo.com> wrote:
Is this not a declaration with initialization, rather than an
assignment?


Well yes it is, but it doesn't make a difference.

<blushing>

Sleeping on the job. Trying to get into the OP's mindset can be
carried too far ;-)

--
Al Balmer
Balmer Consulting
re************* ***********@att .net
Nov 13 '05 #6

"Sheldon Simms" <sh**********@y ahoo.com> wrote in message
news:pa******** *************** **@yahoo.com...
On Thu, 13 Nov 2003 14:31:36 -0700, Alan Balmer wrote:
On Thu, 13 Nov 2003 16:20:04 -0500, Sheldon Simms
<sh**********@y ahoo.com> wrote:
On Thu, 13 Nov 2003 12:26:59 -0800, Minti wrote:

I was reading some text and I came across the following snippet

switch('5')
{
int x = 123;
case '5':
printf("The value of x %d\n", x);
break;
}
Now according to the text the memory would be allocated for the varible x but the value of x would be an intermediate one. Can anybody expain the rationale
The assignment of 123 to x never happens
The code is equivalent to:

goto foo;
{
int x = 123;
foo:
printf("The value of x %d\n", x);
}

-Sheldon


Is this not a declaration with initialization, rather than an
assignment?


Well yes it is, but it doesn't make a difference.

6.8#3
The initializers of objects that have automatic storage duration, ...
are evaluated and the values are stored in the objects ... each time
the declaration is reached in the order of execution, as if it were a
statement

In the examples above, the declaration is never reached and so the
variable is not initialized.

Hello Sheldon,

The contents below the header "6.8#3" seems to be an extract from some
standard document. Could you
please provide me more details about the document and the location where I
can get it.

Thanks and Regards,
Praveen Kumar
Nov 13 '05 #7
"sahukar praveen" <sa************ @yahoo.co.in> writes:
The contents below the header "6.8#3" seems to be an extract from some
standard document. Could you
please provide me more details about the document and the location where I
can get it.


This is in the FAQ.

Section 11. ANSI/ISO Standard C

11.1: What is the "ANSI C Standard?"

A: In 1983, the American National Standards Institute (ANSI)
commissioned a committee, X3J11, to standardize the C language.
After a long, arduous process, including several widespread
public reviews, the committee's work was finally ratified as ANS
X3.159-1989 on December 14, 1989, and published in the spring of
1990. For the most part, ANSI C standardizes existing practice,
with a few additions from C++ (most notably function prototypes)
and support for multinational character sets (including the
controversial trigraph sequences). The ANSI C standard also
formalizes the C run-time library support routines.

More recently, the Standard has been adopted as an international
standard, ISO/IEC 9899:1990, and this ISO Standard replaces the
earlier X3.159 even within the United States (where it is known
as ANSI/ISO 9899-1990 [1992]). As an ISO Standard, it is
subject to ongoing revision through the release of Technical
Corrigenda and Normative Addenda.

In 1994, Technical Corrigendum 1 (TC1) amended the Standard
in about 40 places, most of them minor corrections or
clarifications, and Normative Addendum 1 (NA1) added about 50
pages of new material, mostly specifying new library functions
for internationaliz ation. In 1995, TC2 added a few more minor
corrections.

As of this writing, a complete revision of the Standard is in
its final stages. The new Standard is nicknamed "C9X" on the
assumption that it will be finished by the end of 1999. (Many
of this article's answers have been updated to reflect new C9X
features.)

The original ANSI Standard included a "Rationale, " explaining
many of its decisions, and discussing a number of subtle points,
including several of those covered here. (The Rationale was
"not part of ANSI Standard X3.159-1989, but... included for
information only," and is not included with the ISO Standard.
A new one is being prepared for C9X.)

11.2: How can I get a copy of the Standard?

A: Copies are available in the United States from

American National Standards Institute
11 W. 42nd St., 13th floor
New York, NY 10036 USA
(+1) 212 642 4900

and

Global Engineering Documents
15 Inverness Way E
Englewood, CO 80112 USA
(+1) 303 397 2715
(800) 854 7179 (U.S. & Canada)

In other countries, contact the appropriate national standards
body, or ISO in Geneva at:

ISO Sales
Case Postale 56
CH-1211 Geneve 20
Switzerland

(or see URL http://www.iso.ch or check the comp.std.intern at FAQ
list, Standards.Faq).

The last time I checked, the cost was $130.00 from ANSI or
$400.50 from Global. Copies of the original X3.159 (including
the Rationale) may still be available at $205.00 from ANSI or
$162.50 from Global. Note that ANSI derives revenues to support
its operations from the sale of printed standards, so electronic
copies are *not* available.

In the U.S., it may be possible to get a copy of the original
ANSI X3.159 (including the Rationale) as "FIPS PUB 160" from

National Technical Information Service (NTIS)
U.S. Department of Commerce
Springfield, VA 22161
703 487 4650

The mistitled _Annotated ANSI C Standard_, with annotations by
Herbert Schildt, contains most of the text of ISO 9899; it is
published by Osborne/McGraw-Hill, ISBN 0-07-881952-0, and sells
in the U.S. for approximately $40. It has been suggested that
the price differential between this work and the official
standard reflects the value of the annotations: they are plagued
by numerous errors and omissions, and a few pages of the
Standard itself are missing. Many people on the net recommend
ignoring the annotations entirely. A review of the annotations
("annotated annotations") by Clive Feather can be found on the
web at http://www.lysator.liu.se/c/schildt.html .

The text of the Rationale (not the full Standard) can be
obtained by anonymous ftp from ftp.uu.net (see question 18.16)
in directory doc/standards/ansi/X3.159-1989, and is also
available on the web at http://www.lysator.liu.se/c/rat/title.html .
The Rationale has also been printed by Silicon Press,
ISBN 0-929306-07-4.

Public review drafts of C9X are available from ISO/IEC
JTC1/SC22/WG14's web site, http://www.dkuug.dk/JTC1/SC22/WG14/ .

See also question 11.2b below.

--
"For those who want to translate C to Pascal, it may be that a lobotomy
serves your needs better." --M. Ambuhl

"Here are the steps to create a C-to-Turbo-Pascal translator..." --H. Schildt
Nov 13 '05 #8
Alan Balmer wrote:
.... snip ...
Is this not a declaration with initialization, rather than an
assignment?


Contrary to external appearances, there is no such declaration for
automatic variables. Code must always be generated to perform the
initialization. Which is one reason I prefer to write such code
out myself (it only requires one extra typing of the variable
name, and one extra semi, neither of which appears to create a
desperate shortage).

--
Chuck F (cb********@yah oo.com) (cb********@wor ldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net> USE worldnet address!
Nov 13 '05 #9
In <3F************ ***@yahoo.com> CBFalconer <cb********@yah oo.com> writes:
Alan Balmer wrote:
... snip ...

Is this not a declaration with initialization, rather than an
assignment?


Contrary to external appearances, there is no such declaration for
automatic variables.


Of course there is:

int x;

at block scope.
Code must always be generated to perform the initialization.
Nonsense. The compiler merely has to allocate space for x on a
stack-like data structure, without touching this space. The program
can assign something to x at any time before trying to access its value
for the first time. If this something is not available at the time the
variable is defined, there is no point in providing an initialiser.
Which is one reason I prefer to write such code
out myself (it only requires one extra typing of the variable
name, and one extra semi,


???

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 13 '05 #10

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

Similar topics

5
7447
by: Teddy | last post by:
Hello all consider the code fragment below: case 1: { int i = 1; break; } VC give this error:error C2360: initialization of 'i' is skipped by
11
4273
by: Mark Yudkin | last post by:
The documentation is unclear (at least to me) on the permissibility of accessing DB2 (8.1.5) concurrently on and from Windows 2000 / XP / 2003, with separate transactions scope, from separate threads of a multithreaded program using embedded SQL. Since the threads do not need to share transaction scopes, the sqleAttachToCtx family of APIs do not seem to be necessary. <quote> In the default implementation of threaded applications against...
23
1712
by: NotYetaNurd | last post by:
for(int i=0;i<6;i++) { // } wont i go out of scope after the for loop ...?
10
1270
by: Meya-awe | last post by:
Hi, i am new to C#. I am using some code similar to the one below. I am declaring an ArrayList in one case block but the compiler complains about it already being used in the previous case block. Is this normal in C#? Assume that i follow this and in the first case block, i allocate the memory using the "ArrayList mylist=new ArrayList()", and in the second block, i just use the variable mylist like "mylist.Add(something)". Now if the...
12
1471
by: Andrew Ducker | last post by:
And no, this isn't a complaint about break - I'm very happy to make things explicit. However, why isn't the format something like: switch(myVariable) { case 1: { //Do Something
3
1735
by: apandapion | last post by:
The following code snippet fails to compile with "a local variable named n is already defined in this scope." This makes me uncomfortable, but I could not tell you exactly why. My instincts are telling me that each case should be a seperate block, I guess. Any comments? public class MyClass { public static void Main() {
14
2575
by: Evan Camilleri | last post by:
I am going from VB.NET to c#. How can I do the following? switch x { case < 10: do something; break; case < 50: do something; break;
6
5645
by: easy | last post by:
The following code gives me compiler errors galore telling me that I'm crossing the initalization of the vectors and that case label 2 and default are "within scope of cleanup or variable array". I suspect its the destructors for the vectors that is causing the problem but why are they being called at all? Shouldn't they go out of scope at the closing bracket after default? Putting brackets around the contents of case1 solves my...
5
2239
by: somenath | last post by:
Hi All , I have one question regarding scope and lifetime of variable. #include <stdio.h> int main(int argc, char *argv) { int *intp = NULL; char *sptr = NULL;
0
9680
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9528
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
10455
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...
0
10006
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...
1
7547
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5441
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
5573
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4116
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
3
2925
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.