473,671 Members | 2,558 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Variable vs. child scopes

Hi,

When I try to compile the below code snippet, I get the compile error listed
below in this question. In the lines below the loop, the variable j does not
excist, however, trying to create it is not allowed. If it doesn't excist,
why can't I create it?.

I'm not looking for a solution to this problem - that's quite easy - an
explanation however would be great, as I've been intrigued by this for a
couple of years now.

Thanks Jesper.

Code snippet.

int foo = 0;

for (int j = 0; j < 5; j++)
{
foo += j;
}

int j = 5;
Error 1 A local variable named 'j' cannot be declared in this scope because
it would give a different meaning to 'j', which is already used in a 'child'
scope to denote something else
Oct 24 '07 #1
2 1391
Jesper, Denmark <Je***********@ discussions.mic rosoft.comwrote :
When I try to compile the below code snippet, I get the compile error listed
below in this question. In the lines below the loop, the variable j does not
excist, however, trying to create it is not allowed. If it doesn't excist,
why can't I create it?.

I'm not looking for a solution to this problem - that's quite easy - an
explanation however would be great, as I've been intrigued by this for a
couple of years now.
The scope of a variable is the whole of the block it's declared in,
even though it's not available before it's declared.

From the Unified C# 3 spec, section 3.7:

<quote>
The scope of a local variable declared in a local-variable-declaration
(§8.5.1) is the block in which the declaration occurs.
</quote>

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Oct 24 '07 #2
Jesper wrote:
Hi,

When I try to compile the below code snippet, I get the compile error listed
below in this question. In the lines below the loop, the variable j does not
excist, however, trying to create it is not allowed. If it doesn't excist,
why can't I create it?.

I'm not looking for a solution to this problem - that's quite easy - an
explanation however would be great, as I've been intrigued by this for a
couple of years now.

Thanks Jesper.

Code snippet.

int foo = 0;

for (int j = 0; j < 5; j++)
{
foo += j;
}

int j = 5;
Error 1 A local variable named 'j' cannot be declared in this scope because
it would give a different meaning to 'j', which is already used in a 'child'
scope to denote something else
A variable in a child scope is not allowed to have the same name as a
variable in the parent scope. Not because the compiler wouldn't be able
to figure it out, but because the code would very easily become
confusing to humans.

Take a simple example where you use a variable in a loop:

int j = 1;
for (int i = 0; i < 10; i++) {
Console.WriteLi ne(j);
j = 1 - j;
}

If you would change the code to write each value more than once, and
were allowed to use the same variable name i child scope, you could do:

int j = 1;
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 3; j++) {
Console.WriteLi ne(j);
}
j = 1 - j;
}

This would of course not give the desired result. The code for the
output hasn't changed, but the meaning of the variable has changed. In a
more complex code, it could be very hard to spot the cause of the problem.

--
Göran Andersson
_____
http://www.guffa.com
Oct 24 '07 #3

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

Similar topics

68
4343
by: Marco Bubke | last post by:
Hi I have read some mail on the dev mailing list about PEP 318 and find the new Syntax really ugly. def foo(x, y): pass I call this foo(1, 2), this isn't really intuitive to me! Also I don't like the brackets.
10
2246
by: Blaxer | last post by:
There is probably a really easy way to do this, so please forgive me but I would like to set the value of a variable from a variable, an example would be... function Calculate_Something(ByVal multiplyer as integer, ByVal variable as ___?) variable = 5 * multiplyer end function What I would like this function to do is take the name of the incoming variable and assign a calculated value to it. Any help would be greatly appreciated, TIA!!
37
2768
by: Tim N. van der Leeuw | last post by:
Hi, The following might be documented somewhere, but it hit me unexpectedly and I couldn't exactly find this in the manual either. Problem is, that I cannot use augmented assignment operators in a nested scope, on variables from the outer scope: PythonWin 2.4.3 (#69, Mar 29 2006, 17:35:34) on win32. Portions Copyright 1994-2004 Mark Hammond (mhammond@skippinet.com.au) -
10
12787
by: John Passaniti | last post by:
(Note: This is not the same message I posted a week or so ago. The problem that prevented my previous attempt to work was a silly error in the template system I was using. This is a problem involving variable scope in JavaScript.) I have a lot of code that generates HTML on the fly. This code has tags with id attributes derived from variables. A small example: blah('<span id="' + dev + '_' + mod + '">...</span>');
1
25667
pbmods
by: pbmods | last post by:
VARIABLE SCOPE IN JAVASCRIPT LEVEL: BEGINNER/INTERMEDIATE (INTERMEDIATE STUFF IN ) PREREQS: VARIABLES First off, what the heck is 'scope' (the kind that doesn't help kill the germs that cause bad breath)? Scope describes the context in which a variable can be used. For example, if a variable's scope is a certain function, then that variable can only be used in that function. If you were to try to access that variable anywhere else in...
2
4706
by: Shraddha | last post by:
Can we declare extern variable as static? What will be the scope of the variable then? What if we change the value of the variable in some other function? Also can someone tell me that if we can declare the global variable...and it is having scope throughout the file then what is so different in extern variable???
45
9340
by: loudking | last post by:
Hello, all I don't quite understand what does ((time_t)-1) mean when I execute "man 2 time" RETURN VALUE On success, the value of time in seconds since the Epoch is retu rned. On error, ((time_t)-1) is returned, and errno is set
4
1113
by: Omari Norman | last post by:
Greetings, Take for instance the following code: int main() { int x=5; if (x == 5) { int y = 10;
3
2040
by: SRoubtsov | last post by:
Dear all, Do you know whether ANSI C (or some other dialects) support the following: * a variable name coincides with a type name, * a structure/union field name coincides with a type name in the same file (.c + all relevant .h's)? e.g.
0
8485
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
8403
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
8930
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
8828
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
8605
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
8677
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
6238
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
4227
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
4417
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.