Thread: simple scope question

  1. #1
    Registered User
    Join Date
    Apr 2003
    Posts
    2,663

    simple scope question

    Hi,

    Can someone tell me how the following simple examples work? In the first one, 'i' goes out of scope after being assigned to a variable outside the block. How does the outer variable have a value after the block that 'i' is in ends? Does a copy of 'i' get assigned to the outer variable, so that when the local variable is destroyed, it doesn't affect the outer variable?

    In the second example, the inner ariable is an array, and it's address is assigned to the outer variable. When the inner array goes out of scope, how does the outer variable still contain a valid address?

    Code:
    #include<iostream>
    using namespace std;
    
    
    int main()
    {
    	//test1 ***
    	
    	int outerA;
    		
    	if(true)
    	{
    		int i = 10;
    		outerA = i;
    	}
    	
    	cout<<outerA<<endl;
    
    	//******************
    	
    	
    	//test2 ***
    	
    	int* outerB;
    
    	if(true)
    	{
    		int my_array[3] = {1, 2, 3};
    		outerB = my_array;
    	}
    
    	cout<<outerB[0]<<endl;
    	
    	//*******************
    	
    	return 0;
    }
    Last edited by 7stud; 01-29-2005 at 12:55 AM.

  2. #2
    Banned
    Join Date
    Oct 2004
    Posts
    250
    globalA isent evan a global variable it has a scope of the main function. A global variable is one that is delcared outside of any function.

  3. #3
    Registered User
    Join Date
    Apr 2003
    Posts
    2,663
    globalA isent evan a global variable
    ...which has nothing to do with the question. I'll edit the variable names.

  4. #4
    vae victus! skorman00's Avatar
    Join Date
    Nov 2003
    Posts
    594
    You could say that the value gets coppied into the outer variable. Variables are just blocks of memory that hold values. When you assigned outerA to i (outerA = i; ) the value in i's block was put into outerA's block. Once you get out of that if statement, i's block goes away, but the value is still stored in A's block. Same thing with outerB and the array.

  5. #5
    Registered User major_small's Avatar
    Join Date
    May 2003
    Posts
    2,787
    if i'm reading you right, this is the block of code in question:
    Code:
        int outerA;
            
        if(true)
        {
            int i = 10;
            outerA = i;
        }
        
        cout<<outerA<<endl;
    basically, i's scope is only within the if block, and outerA's scope is the entire main routine. for now you can define scope as the curly brackets. outerA is assigned the value contained in i, and that is why that last cout outputs what appears to be i.

    an example using the curly brackets:
    Code:
    int A=0;
    {
         int B=10;
         A=B;
    }cout<<A;
    in that example, blue is the scope A is in, and red is the scope B is in. the purple is where they overlap. as you can see, A moves into the curly brackets and comes back out because it is defined outside of them.
    Join is in our Unofficial Cprog IRC channel
    Server: irc.phoenixradio.org
    Channel: #Tech


    Team Cprog Folding@Home: Team #43476
    Download it Here
    Detailed Stats Here
    More Detailed Stats
    52 Members so far, are YOU a member?
    Current team score: 1223226 (ranked 374 of 45152)

    The CBoard team is doing better than 99.16% of the other teams
    Top 5 Members: Xterria(518175), pianorain(118517), Bennet(64957), JaWiB(55610), alphaoide(44374)

    Last Updated on: Wed, 30 Aug, 2006 @ 2:30 PM EDT

  6. #6
    Registered User
    Join Date
    Apr 2003
    Posts
    2,663
    if i'm reading you right, this is the block of code in question:

    int outerA;

    if(true)
    {
    int i = 10;
    outerA = i;
    }

    cout<<outerA<<endl;
    Ok, I can understand that one. What about the second example?

    the value is still stored in outerA's block. Same thing with outerB and the array.
    In the second example, it seems to me that outerB gets assigned an address of the array. When the array goes out of scope, why is the address stored in outerB still valid? Doesn't the memory for the array get released?

    What if the 'outer' variable were assigned the address of a class object which was declared in the inner scope? Wouldn't the object's destructor destroy the object when exiting the inner scope?
    Last edited by 7stud; 01-29-2005 at 02:32 AM.

  7. #7
    Registered User
    Join Date
    Aug 2003
    Posts
    1,218
    It is not valid memory, at any time some other program can overwrite the memory and therefore the pointer points to bad memory. This is something you will have to consider when using pointers. This can be shown with this little example:
    Code:
    #include <iostream>
    using namespace std;
    
    class Foo
    {
    public:
        Foo() { cout << "Foo constructor" << endl; }
        ~Foo() { cout << "Foo destructor" << endl; }
    };
    
    int main()
    {
        Foo* bar;
        {
             cout << "New scope" << endl;
             Foo temp;
             bar = &temp;
             cout << "Back to main scope" << endl;
        }
        cout << "In main scope" << endl;
        // Now bar points to bad memory and should not ever be used here without being reassigned to different memory
        cin.get();
    }
    Last edited by Shakti; 01-29-2005 at 03:18 AM.

  8. #8
    Registered User
    Join Date
    Apr 2003
    Posts
    2,663
    Hi,

    But the array example works: the output is 1. My question is why? Why is the array example like assigning a simple type and not like assigning a class object? In the array example, it seems to me you are assigning a pointer to the outer variable which points to an address in memory which contains the array, and then the array goes out of scope, so why can you still access the array? Shouldn't it no longer exist?

    Variables are just blocks of memory that hold values. When you assigned outerA to i (outerA = i; ) the value in i's block was put into outerA's block. Once you get out of that if statement, i's block goes away, but the value is still stored in A's block. Same thing with outerB and the array.
    Applying that to the array, shouldn't outerB's block of memory contain the address of the inner array?
    Last edited by 7stud; 01-29-2005 at 04:56 AM.

  9. #9
    Registered User
    Join Date
    Aug 2003
    Posts
    1,218
    It doesnt exist. It is just dumb luck that it works.

  10. #10
    Registered User
    Join Date
    Apr 2003
    Posts
    2,663
    It doesnt exist. It is just dumb luck that it works.
    It would make sense to me if the inner int was copied to the outer variable so it was accesible, and the array and class object were not copied, and therefore were no longer accessible. However, I ran the following code, which assigns an inner int, an inner array, and an inner class object to an outer variable, and I am able to access all three after the inner variable goes out of scope. Do I have to take it on faith that the array and the class object really shouldn't be accessible. (Btw, I'm using VC++6)
    Code:
    #include<iostream>
    using namespace std;
    
    class CCC
    {
    public:
        
        int num;
    };
    
    int main()
    {
        //test1 ***
        
        int outerA;
            
        if(true)
        {
            int i = 10;
            outerA = i;
        }
        
        cout<<outerA<<endl;
    
        //******************
        
        
        //test2 ***
        
        int* outerB;
    
        if(true)
        {
            int my_array[3] = {1, 2, 3};
            outerB = my_array;
        }
    
        cout<<outerB[0]<<endl;
        
        //*******************
    
        //test3 *****
    
        
        CCC* outerC;
    
        if(true)
        {
            CCC a;
            a.num=10;
    
            CCC* p = &a;
            outerC = p;
        }
        
        cout<<outerC->num<<endl;
    
        return 0;
    }
    Last edited by 7stud; 01-29-2005 at 06:49 AM.

  11. #11
    Registered User
    Join Date
    Aug 2003
    Posts
    1,218
    Your example "works" (not really because its still memory that isnt valid) but this doesnt:
    Code:
    #include<iostream>
    using namespace std;
    
    class CCC
    {
    public:
        int num;
    };
    
    int main()
    {
        //test1 ***
        
        int outerA;
            
        if(true)
        {
            int i = 10;
            outerA = i;
        }
        
        cout<<outerA<<endl;
    
        //******************
        
        
        //test2 ***
        
        int* outerB;
    
        if(true)
        {
            int my_array[3] = {1, 2, 3};
            outerB = my_array;
        }
        int my_array2[3] = { 8,6,7 };
        cout<<outerB[0]<<endl;
        
        //*******************
    
        //test3 *****
    
        
        CCC* outerC;
    
        if(true)
        {
            CCC a;
            a.num=10;
    
            outerC = &a;
        }
        CCC b;
        b.num = 80;
        cout<<outerC->num<<endl;
    
        cin.get();
        return 0;
    }
    On my computer this gives me an output of:
    10
    8
    80

    So we can clearly see that the memory where my_array[3] is stored has been overwritten by the my_array2[3], same with CCC a and CCC b.

  12. #12
    vae victus! skorman00's Avatar
    Join Date
    Nov 2003
    Posts
    594
    Remember what I was saying about blocks of memory? Those blocks reserved for the array still hold those values, but after the array goes to scope, you shouldn't be touching it.

    Picture it like this: Somebody creates a row of bakeries (the array). After a while, people no longer need so many bakers, so they all go outta business (the array goes outta scope). However, the bakers didn't clean up after they left. You can still go into those buildings and grab some bread, but you shouldn't. What if one day somebody else will claim that space for a row of manure outlets? You'll go in there thinking you're about to get a nice bagel, and BAM!!!! Your day is ruined!
    Last edited by skorman00; 01-29-2005 at 08:57 PM.

  13. #13
    Handy Andy andyhunter's Avatar
    Join Date
    Dec 2004
    Posts
    540
    hmm, so how is an object factory different? I guess I have some misunderstanding here.
    i don't think most standard compilers support programmers with more than 4 red boxes - Misplaced

    It is my sacred duity to stand in the path of the flood of ignorance and blatant stupidity... - quzah

    Such pointless tricks ceased to be interesting or useful when we came down from the trees and started using higher level languages. - Salem

  14. #14
    vae victus! skorman00's Avatar
    Join Date
    Nov 2003
    Posts
    594
    An object factory is usually used to deal with dynamic memory, that way cleanup is easy. It's a concept, so there's no concrete way in implimenting one. It could very well have the same results as this situation.

  15. #15
    Handy Andy andyhunter's Avatar
    Join Date
    Dec 2004
    Posts
    540
    I mean you return the object you create in the function. Wouldn't this cause it to be unsecured memory? I always thought that as long as there was a viable pointer to a memory location than the object persisted, such as COM implementation.
    i don't think most standard compilers support programmers with more than 4 red boxes - Misplaced

    It is my sacred duity to stand in the path of the flood of ignorance and blatant stupidity... - quzah

    Such pointless tricks ceased to be interesting or useful when we came down from the trees and started using higher level languages. - Salem

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. simple question.
    By InvariantLoop in forum Windows Programming
    Replies: 4
    Last Post: 01-31-2005, 12:15 PM
  2. A simple question about scope
    By dwylie in forum C Programming
    Replies: 3
    Last Post: 12-10-2004, 01:16 PM
  3. Binary Search Trees Part III
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 10-02-2004, 03:00 PM
  4. simple fgets question
    By theweirdo in forum C Programming
    Replies: 7
    Last Post: 01-27-2002, 06:58 PM
  5. Scope question
    By mikebrewsj in forum C++ Programming
    Replies: 1
    Last Post: 01-17-2002, 04:47 PM