martega
martega

Reputation: 2143

Some explanation required regarding the scope of my variable

/* simple class that has a vector of ints within it */
class A
{
public:
   vector<int> int_list;
};

/* some function that just returns an int, defined elsewhere */
int foo();

/* I want to fill the object's int_list up */
A a_obj;

int main() {
   for (int i = 0; i < 10; i++) {
      int num = foo();
      a_obj.int_list.push_back( num );
   }
}

Is the scope of num limited to the for loop? Will it be destroyed once the for loop is exited? If I try to access the numbers in a_obj's int_list will I not be able to as the numbers inside will have been destroyed?

Upvotes: 1

Views: 84

Answers (4)

cpx
cpx

Reputation: 17577

Is the scope of num limited to the for loop? Will it be destroyed once the for loop is exited?

Yes, because num is local to for-loop.

If I try to access the numbers in a_obj's int_list will I not be able to as the numbers inside will have been destroyed?

No, the numbers inside list won't be destroyed when it exits the for-loop because you're copying the numbers to the list and A a_obj; is declared in global scope which means it gets destroyed at the end of your program.

Upvotes: 1

Pepe
Pepe

Reputation: 405

yea, each time the for loop iterates it creates a new instance of num on the stack. but you are passing the value of num into int_list where it will be stored until a_obj goes out of scope

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409462

Yes, variables defined within the loop, or any block of { ... } will exist only inside that block, and will be destroyed when leaving the block.

In the case of loops, the block will be "created" every iteration, so in your example num can not be referenced from earlier iterations.

Upvotes: 0

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385385

Is the scope of num limited to the for loop?

Yes

Will it be destroyed once the for loop is exited?

It'll be destroyed after each iteration, and then created again for the next!

If I try to access the numbers in a_obj's int_list will I not be able to as the numbers inside will have been destroyed?

Containers store copies, so you don't have to worry about this.

You only run into these sorts of issues with references and pointers.

Upvotes: 5

Related Questions