473,657 Members | 2,733 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

scope

Hi there,

I mainly use c for programming but have decided to try and learn c++.
I found a text which delcares the following

{
int *variablePointe r;
int count = 32;
variablePointer = &count;
cout << *variablePointe r;
}

This I understand as it is very similar in c. My belief is that
variablePointer is a pointer to an int. count is declared as an int and
initialised to 32. variablePointer is then set to point to count, and
therefore has value 32 when cout is called.
My problem is then in the following example which is supposedly wrong:
{
int *variablePointe r;
{
int count = 32;
variablePointer = &count;
}
cout << *variablePointe r;
}

I just want to clarigy if I understand why this is wrong.
variablePointer again is a pointer to an int and has scope within the
whole of the above function. We then enter a new scope sub-level, and
count is decalred as an int and initialised to the value of 32.
variablePointer is set to point to count. We then leave this scope
level, and when we try to use cout for variablePointer , we are causing
undefined behaviour. Is this a correct assumption?
Thanks
Allan

Jul 19 '05 #1
2 2685
Allan Bruce wrote:
<snip>

This I understand as it is very similar in c. My belief is that
variablePointer is a pointer to an int. count is declared as an int and
initialised to 32. variablePointer is then set to point to count, and
therefore has value 32 when cout is called.
My problem is then in the following example which is supposedly wrong:
{
int *variablePointe r;
{
int count = 32;
variablePointer = &count;
}
cout << *variablePointe r;
}
Not supposedly - it *is* wrong.

The variable 'count' will go out of scope after you take a pointer to
it, and before you dereference that pointer. The closest analogy I can
think of in C-like code is:

int* varptr = (int*)malloc(si zeof int);
*varptr = 32;
free(varptr);
printf("%d", *varptr);

Since the memory is no longer allocated to an object, the system is free
to use it for anything... and your pointer is no longer valid. The
chances are that you'll find that it has been written to before you get
to dereferencing the pointer. And if you (or the compiled code) do
anything else between count going out of scope and dereferencing the
pointer, then the probability of the value remaining unmodified
approaches zero.

In the specific example you quoted, depending on what's going on behind
the scenes, I'd say you have a fairly good chance that the stack space
you're pointing to still contains the value count had before it went out
of scope. However, relying on this to be true is a fundamentally
*wrong* practice that *will* cause you problems in future.
I just want to clarigy if I understand why this is wrong.
variablePointer again is a pointer to an int and has scope within the
whole of the above function. We then enter a new scope sub-level, and
count is decalred as an int and initialised to the value of 32.
variablePointer is set to point to count. We then leave this scope
level, and when we try to use cout for variablePointer , we are causing
undefined behaviour. Is this a correct assumption?


Err.. see above :)

(I must remember to re-read to the bottom before responding... *sigh*)

--
Corey Murtagh
The Electric Monk
"Quidquid latine dictum sit, altum viditur!"

Jul 19 '05 #2

"Allan Bruce" <no*******@notc sd.abdn.ac.uk> wrote in message
news:3E******** ******@notcsd.a bdn.ac.uk...
Hi there,

I mainly use c for programming but have decided to try and learn c++.
I found a text which delcares the following

{
int *variablePointe r;
int count = 32;
variablePointer = &count;
cout << *variablePointe r;
}

This I understand as it is very similar in c. My belief is that
variablePointer is a pointer to an int. Correct
count is declared as an int and
initialised to 32. Correct
variablePointe r is then set to point to count, and
therefore has value 32 when cout is called. VariablePointer does NOT hold 32..it holds the address of count which holds
32.
My problem is then in the following example which is supposedly wrong:
{
int *variablePointe r;
{
int count = 32;
variablePointer = &count;
}
cout << *variablePointe r;
}

I just want to clarigy if I understand why this is wrong.
variablePointer again is a pointer to an int and has scope within the
whole of the above function. We then enter a new scope sub-level, and
count is decalred as an int and initialised to the value of 32.
variablePointer is set to point to count. We then leave this scope
level, and when we try to use cout for variablePointer , we are causing
undefined behaviour. Is this a correct assumption? Yes..variablePo inter was pointing to count which gets destroyed when it's
enclosing block terminates.
Thus variablePointer still holds an address that system is free to use at
it's will and should not be accessed.
Thanks
Allan

Jul 19 '05 #3

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

Similar topics

3
6461
by: Anonymous | last post by:
Is namespace the same thing as scope? While reading the book "Thinking in C++", I was under the impression that namespace is, well, a namespace--a feature to create a hiearchy for identifiers within the Global Namespace. And that, all identifiers within a given namespace, however deeply nested they are, each of them has the Global Scope. So, if namespace outer { int a = 1;
6
3150
by: pembed2003 | last post by:
Hi all, I am reading the book "C++ How to Program" and in the chapter where it discuss scope rule, it says there are four scopes for a variable: function scope file scope block scope function-prototype scope I think(might be wrong):
5
2085
by: pembed2003 | last post by:
Hi all, I am reading the book "C How to Program" and in the chapter where it discuss scope rule, it says there are four scopes for a variable: function scope file scope block scope function-prototype scope I think(might be wrong):
8
3367
by: TTroy | last post by:
I have a few questions about "scope" and "visibility," which seem like two different things. To me "visibility" of the name of a function or object is the actual code that can use it in an actual program. To me "scope" of the name of a function or object are the general rules for the areas of a program that can through a declaration, have "visibility."
3
3426
by: marco_segurini | last post by:
Hi, I am using VS 2005. If I compile the following code only line 6 returns me an error while line 9 returns a warning. If I comment the line 6 and debug the program the assignments of lines {9, 11} work fine. Why the '.' "scope operator" is accepted in line 9 and not in line 6?
39
3175
by: utab | last post by:
Dear all, Is there a clear distinction how to decide which functions to be members of a class and which not How is your attitude (Your general way from your experiences ...) "If the function changes the state of the object, it ought to be a member of that object." Reference Accelerated C++, A. Koenig, page 159.
7
2177
by: Christian Christmann | last post by:
Hi, I've a a question on the specifier extern. Code example: void func( void ) { extern int e; //...
1
2576
by: Steven T. Hatton | last post by:
All of the following terms are used in some way to describe where and how a name is relevant to a particular location in a program: visible, declarative region, scope, potential scope, valid, introduced, used, potentially evaluated and accessible. They all seem to have subtle difference in meanings. Any positive contribution to the following will be appreciated. Here is my attempt to make sense of these:
1
25664
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...
1
3755
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
8306
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
8732
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
8503
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
7327
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5632
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4152
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
4304
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2726
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
1615
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.