Thread: simple scope question

Threaded View

Previous Post Previous Post   Next Post Next Post
  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.

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