473,782 Members | 2,396 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

do/while loop and scope of automatic vars

Hi all,

Consider the following code snippet:

do
{
int r = rand () ;
} while (r != 0) ;

It seems the compiler I'm using (GCC) does realise that the
scope of variable r extends the end of the while's conditional.

Questions:

- Is this correct according to the ISO/ANSI C standards?
- If so, can someone point me to the section of the ISO
C99 stanard whic defines this?

TIA,
Erik
--
-----------------------------------------------------------------
Erik de Castro Lopo
-----------------------------------------------------------------
Of the four project development variables - scope, cost, time and
quality - quality isn't really a free variable. The only possible
values are "excellent" and "insanely excellent", depending on
whether lives are at stake." -- Kent Beck, XP Explained
Aug 21 '07 #1
8 4531
Erik de Castro Lopo <er***@mega-nerd.comwrites:
Consider the following code snippet:

do
{
int r = rand () ;
} while (r != 0) ;

It seems the compiler I'm using (GCC) does realise that the
scope of variable r extends the end of the while's conditional.

Questions:

- Is this correct according to the ISO/ANSI C standards?
- If so, can someone point me to the section of the ISO
C99 stanard whic defines this?
Did you mean to write that it *doesn't" realize that the scope extends
to the end of the conditional?

When I wrap your code in a main program and compile it with gcc, I get:

c.c: In function `main':
c.c:7: error: `r' undeclared (first use in this function)
c.c:7: error: (Each undeclared identifier is reported only once
c.c:7: error: for each function it appears in.)

gcc is correct. C99 6.2.1p4 says:

If the declarator or type specifier that declares the identifier
appears inside a block or within the list of parameter
declarations in a function definition, the identifier has _block
scope_, which terminates at the end of the associated block.

The block extends from the opening '{' to the closing '}'.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Aug 21 '07 #2
On Aug 20, 11:01 pm, Erik de Castro Lopo <er...@mega-nerd.comwrote:
Hi all,

Consider the following code snippet:

do
{
int r = rand () ;
} while (r != 0) ;

It seems the compiler I'm using (GCC) does realise that the
scope of variable r extends the end of the while's conditional.
Because it doesn't.
>
Questions:

- Is this correct according to the ISO/ANSI C standards?
No.
- If so, can someone point me to the section of the ISO
C99 stanard whic defines this?
§6.2.1p4:
"...If the declarator or type specifier that declares the identifier
appears inside a block or within the list of parameter declarations in
a function definition, the identifier has block scope, which
terminates at the end of the associated block."

§6.8.5p4-5
"An iteration statement causes a statement called the loop body to be
executed repeatedly
until the controlling expression compares equal to 0.

An iteration statement is a block whose scope is a strict subset of
the scope of its
enclosing block. The loop body is also a block whose scope is a strict
subset of the scope
of the iteration statement."

The loop body is a block, the variable r is declared in this block.
The scope of the variable extends to the end of the associated block
of which the controlling expression is not a part.

Robert Gamble

Aug 21 '07 #3
Erik de Castro Lopo wrote:
Hi all,

Consider the following code snippet:

do
{
int r = rand () ;
} while (r != 0) ;

It seems the compiler I'm using (GCC) does realise that the
scope of variable r extends the end of the while's conditional.
The scope of the `r' inside the { } ends at the closing }.
The `r' in the while clause is some other `r' from an enclosing
scope.
Questions:

- Is this correct according to the ISO/ANSI C standards?
- If so, can someone point me to the section of the ISO
C99 stanard whic defines this?
6.8.5p5: "An iteration statement is a block whose scope is
a strict subset of the scope of its enclosing block. The loop
body is also a block whose scope is a strict subset of the scope
of the iteration statement."

See also 6.2.1p4 for the definition of "block scope."

--
Eric Sosman
es*****@ieee-dot-org.invalid
Aug 21 '07 #4
Erik de Castro Lopo wrote:
>
Consider the following code snippet:

do
{
int r = rand () ;
} while (r != 0) ;

It seems the compiler I'm using (GCC) does realise that the
scope of variable r extends the end of the while's conditional.

Questions:

- Is this correct according to the ISO/ANSI C standards?
- If so, can someone point me to the section of the ISO
C99 stanard whic defines this?
Consider that rand may never return the value 0, in which case the
loop will run forever. The only possible use of this is to advance
the rand generator to the point where it has just returned zero.
The value(s) returned are not available anywhere. And that is IF
the scope of r extends through the conditional, which may not be so
for another compiler. Whether or not it should is another matter
entirely.

Simpler code with the same faults and no scope problem is:

do {
/* nada */
} while (rand());

--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net>

--
Posted via a free Usenet account from http://www.teranews.com

Aug 21 '07 #5
CBFalconer wrote:
>
Erik de Castro Lopo wrote:

Consider the following code snippet:

do
{
int r = rand () ;
} while (r != 0) ;

It seems the compiler I'm using (GCC) does realise that the
scope of variable r extends the end of the while's conditional.

Questions:

- Is this correct according to the ISO/ANSI C standards?
- If so, can someone point me to the section of the ISO
C99 stanard whic defines this?
My C90 compiler doesn't allow this. As others have pointed out,
"r" is not in scope outside of the loop, and should not exist for
the "while" statement.
Consider that rand may never return the value 0, in which case the
loop will run forever. The only possible use of this is to advance
the rand generator to the point where it has just returned zero.
I took this as simply a sample snippet to demonstrate the "should
'r' be in scope for the 'while' statement" question, not as a
real-life code snippet. We often post "useless" snippets of code
here, simply to boil it down to the simplest wasy of demonstrating
what we are asking.

[...]

--
+-------------------------+--------------------+-----------------------+
| Kenneth J. Brody | www.hvcomputer.com | #include |
| kenbrody/at\spamcop.net | www.fptech.com | <std_disclaimer .h|
+-------------------------+--------------------+-----------------------+
Don't e-mail me at: <mailto:Th***** ********@gmail. com>
Aug 21 '07 #6
On Tue, 21 Aug 2007 15:04:57 -0400, Kenneth Brody wrote:
I took this as simply a sample snippet to demonstrate the "should
'r' be in scope for the 'while' statement" question, not as a
real-life code snippet. We often post "useless" snippets of code
here, simply to boil it down to the simplest wasy of demonstrating
what we are asking.
<ot>
In the comp.lang.c++ FAQ there is a snippet of code which, to show
a situation in which different functions could be called without
being able to know which one at compile time, used to use
srand(time(0)); switch(rand() % 3). But recently it was changed to
switch ((rand() >8) % 3) because "the ">8" (typically)
improves the period of the lowest 2 bits".
(And of course n % 3 depends on *all* of the bits of n, and the
shift does nothing but worsen the bias due to RAND_MAX + 1 not
being a multiple of 3.)
</ot>
--
Army1987 (Replace "NOSPAM" with "email")
No-one ever won a game by resigning. -- S. Tartakower

Aug 22 '07 #7
Army1987 wrote:
>
On Tue, 21 Aug 2007 15:04:57 -0400, Kenneth Brody wrote:
I took this as simply a sample snippet to demonstrate the "should
'r' be in scope for the 'while' statement" question, not as a
real-life code snippet. We often post "useless" snippets of code
here, simply to boil it down to the simplest wasy of demonstrating
what we are asking.

<ot>
In the comp.lang.c++ FAQ there is a snippet of code which, to show
a situation in which different functions could be called without
being able to know which one at compile time, used to use
srand(time(0)); switch(rand() % 3). But recently it was changed to
switch ((rand() >8) % 3) because "the ">8" (typically)
improves the period of the lowest 2 bits".
(And of course n % 3 depends on *all* of the bits of n, and the
shift does nothing but worsen the bias due to RAND_MAX + 1 not
being a multiple of 3.)
</ot>
They were probably thinking of (n % 4) and got confused.

--
pete
Aug 22 '07 #8
pete wrote:
>
Army1987 wrote:
[...]
<ot>
In the comp.lang.c++ FAQ there is a snippet of code which, to show
a situation in which different functions could be called without
being able to know which one at compile time, used to use
srand(time(0)); switch(rand() % 3). But recently it was changed to
switch ((rand() >8) % 3) because "the ">8" (typically)
improves the period of the lowest 2 bits".
(And of course n % 3 depends on *all* of the bits of n, and the
shift does nothing but worsen the bias due to RAND_MAX + 1 not
being a multiple of 3.)
</ot>

They were probably thinking of (n % 4) and got confused.
Or (n & 3).

--
+-------------------------+--------------------+-----------------------+
| Kenneth J. Brody | www.hvcomputer.com | #include |
| kenbrody/at\spamcop.net | www.fptech.com | <std_disclaimer .h|
+-------------------------+--------------------+-----------------------+
Don't e-mail me at: <mailto:Th***** ********@gmail. com>
Aug 22 '07 #9

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

Similar topics

33
3554
by: Arthur | last post by:
>>>a= >>> for p in a: print p 1 2 3 >>> p 3 My naive expectation was that p would be 'not defined' from outside
0
1014
by: Ori Berger | last post by:
I *think* I saw a post some time ago enabling "spreadsheet" like computations, that allows something along the lines of: >>> vars.a = 10 >>> vars.b = dependency("vars.a * 20") >>> print vars.b 200 >>> vars.a = 50 >>> print vars.b 1000
0
1179
by: Uwe Mayer | last post by:
Hi, I've got a class that receives a function in the constructor and uses the __call__ method to execute the aforementioned function when the instance object is called: class foo(object): def __init__(self, func): self.func = func def __call__(self, *arg, **kwarg):
39
2641
by: vineoff | last post by:
If I'm having nested loops like: for (...) for (..) for (...) { /* exit here */ } and I need to exit from there ^ . Is it better to use exceptions or goto or some other method?
9
4179
by: JS | last post by:
#include <stdio.h> main(){ int c, i, nwhite, nother; int ndigit; nwhite = nother = 0; for (i = 0; i < 10; ++i)
36
2815
by: invni | last post by:
I have a nested while. How do I go from the inner while to the beginning of the outer while? Can this be done without using goto? while_1() { some codes here while_2() { if true go to the beginning of while_1 }
8
7519
by: SM | last post by:
I've always wonder if there is diference when declaring and initializing a varible inside/outside a loop. What's a better practice? Declaring and initializing variables inside a loop routine, like this: for(var i=0; i<list; i++) { var name = list; }
5
6135
by: chromis | last post by:
Hi there, I've recently been updating a site to use locking on application level variables, and I am trying to use a commonly used method which copies the application struct into the request scope. Application variables are then accessed in this manner Request.App.<Var>. To begin with I had a simple functioning login system inside a subdirectory named admin, this subdirectory had it's own application.cfm, I wasn't sure whether to duplicate...
1
3760
by: Giacomo Catenazzi | last post by:
Hello, To learn the details of C, I've build the following example, could you check if it is correct and if it miss some important cases? Are there some useful (real cases) examples of: - "function prototype scope" for structures and unions? - "extern" for internal linkage ?
0
9641
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
9480
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
10146
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10080
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
9944
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
7494
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
5511
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4044
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
2875
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.