Question on switch block scope

M

Minti

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?

--
**** 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
 
S

Sheldon Simms

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
 
E

Eric Sosman

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.
**** 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?
 
A

Alan Balmer

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?
 
S

Sheldon Simms

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.
 
B

Ben Pfaff

sahukar praveen said:
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 internationalization. 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.internat 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.
 
S

sahukar praveen

Sheldon Simms said:
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
 
C

CBFalconer

Alan said:
.... 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).
 
D

Dan Pop

In said:
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
 
M

Minti

Sheldon Simms said:
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);
}

Thanks Sheldon, but could you tell me when is the memory for x
allocated. If it has to be allocated when we get into the block after
the statement

goto foo;

Then obviously we can't use x at any place. Or is it the case that
that space would be reserved for x, or any other variable within the
immediate scope of the switch block but it's value would not be
initialized for the given initialization value.
 
S

Sheldon Simms

Thanks Sheldon, but could you tell me when is the memory for x
allocated. If it has to be allocated when we get into the block after
the statement

goto foo;

Then obviously we can't use x at any place. Or is it the case that
that space would be reserved for x, or any other variable within the
immediate scope of the switch block but it's value would not be
initialized for the given initialization value.

We don't know or care when space for the object named x is reserved,
but we know that x is in scope and accessible from the point of its
declaration to the end of the block in which it is declared. The
C Standard puts it like this:

6.2.1
2 For each different entity that an identifier designates, the
identifier is visible (i.e., can be used) only within a region
of program text called its scope.

4 If the declarator or type specifier that declares the identifier
appears inside a block ... the identifier has block scope, which
terminates at the end of the associated block.

This means that we can use x anywhere inside the block after it is
declared, regardless of whether or not it has been initialized. It
does not mean that our use of x has defined behavior.

-Sheldon
 
C

CBFalconer

Dan said:
Of course there is:

int x;

at block scope.


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.

We are not even disagreeing. Your example is a declaration with
no initialization statement. I was talking about declarations
with initialization statements, and whether they generate code.
Because they do, there is really no such thing.
 
M

Minti

Eric Sosman said:
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.

That is why I suggested a little alternative to to just the part of
declaring variable within a {} that encloses the switch block, my
main reason for asking the question was since

int x = 32;

is a declaration with initialization I was confused why the
declaration would only be 'executed' i.e. why only the memory for x
would be allocated but not initialized even though they form one
single statement.

<snip>
 
K

Kevin Bracey

In message <[email protected]>
Sheldon Simms said:
We don't know or care when space for the object named x is reserved,
but we know that x is in scope and accessible from the point of its
declaration to the end of the block in which it is declared.

I think we do care, although not in this example. Minti's question is
answered by distinguishing the "lifetime" from the "scope".

x's lifetime extends from the start of its enclosing block to the end. Thus
in the following example:

int *p = NULL;
{
label:
if (p) printf("x = %d\n", *p);

int x = 5;

printf("x = %d\n", x);

x = 10;

if (!p)
{
p = &x;
goto label;
}
}

You will get the output

x = 5
x = 10
x = 5

Although x isn't in scope at the first printf, it still exists, and you
can reference it through the pointer p.

So, from the abstract machine's point of view, x is "allocated", but
uninitialised when the { } block is entered and "deallocated" when the block
is exited. It is initialised (or re-initialised) whenever execution reaches
its declaration/initialiser.

An actual implementation does not have to actually "allocate" or "deallocate"
x there - it may reserve space for it on function entry, for example,
regardless of whether the block is entered. But that's not the C programmer's
business. For you, the scope extends from the declaration to the end of the
block, and the lifetime from block entry to block exit.

PS - never write code like that
PPS - the example is C99
PPPS - a worse example is in the C99 rationale
 
K

Kevin P. Fleming

Kevin said:
An actual implementation does not have to actually "allocate" or "deallocate"
x there - it may reserve space for it on function entry, for example,
regardless of whether the block is entered. But that's not the C programmer's
business. For you, the scope extends from the declaration to the end of the
block, and the lifetime from block entry to block exit.

I don't follow this; if 'x' was not in scope in the first line of the
block (because the declaration was two lines later), then references to
'x' at that point would have to resolve to some _other_ declaration of
'x' that _is_ in scope, not the one in this block. The example you gave
showed that both the lifetime _and_ the scope of x are the entire
enclosing block.
 
K

Kevin Bracey

In message <V7Nub.18630$vJ6.6629@fed1read05>
"Kevin P. Fleming said:
I don't follow this; if 'x' was not in scope in the first line of the
block (because the declaration was two lines later), then references to
'x' at that point would have to resolve to some _other_ declaration of
'x' that _is_ in scope, not the one in this block.

Indeed, they would.
The example you gave showed that both the lifetime _and_ the scope of x
are the entire enclosing block.

I don't think so. No, the first printf accessed x through a pointer
which was in scope:

if (p) printf("x = %d\n", *p);

If I'd just written

printf("x = %d\n", x);

that would have been an error, or the wrong x would have been used.
 
K

Kevin P. Fleming

Kevin said:
I don't think so. No, the first printf accessed x through a pointer
which was in scope:

if (p) printf("x = %d\n", *p);

If I'd just written

printf("x = %d\n", x);

that would have been an error, or the wrong x would have been used.

OK, yeah, I missed that subtlety. Well, actually I saw it, but my brain
passed it off as irrelevant. It wasn't :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,104
Messages
2,570,643
Members
47,247
Latest member
youngcoin

Latest Threads

Top