Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Scope of variable defined inside a block in C++

Status
Not open for further replies.

Wuu

Technical User
Nov 18, 2007
33
US
Hi,

Suppose I have the following piece of code
Code:
int main()
{
 int A;
 //expressions

   if
   {
      int B;
      //expressions
   }
   else
   {
     //expressions
   }

   return 0;
}

My question is

1. Is it valid in C++ to define a variable such as the integer B inside the "if" block?
2. Can we use this integer outside of the "if" block?
 
Just a little explanation: it's not if block declaration. You declare B in a compound statement or block (in {...}, see C++ Standard).
 
Thanks for your quick reply, cpjust. And to ArkM,I am new to C++, so not really familiar with the terminology and some concept, thanks for pointing out that.

One more question is

if i declare another global variable int B, after the if/else statement, would it cause any problem? I mean would the compiler delete or release the memory allocated to the int B declared inside the if statement?


Thanks
 
Declaring int B after the if/else statement would be a local variable, not a global one. It will not cause any problems, because there is no variable B known at that point of declaration. Local variables are allocated on the stack, the compiler does not delete or release them, nor does it have to. Only the stack pointer is adjusted when the variable goes out of scope.
Only when you create a local variable which is a pointer you must free or release it yourself before it goes out of scope.
Example:
Code:
Something *pSomething = new Something();
// new Something() has created the class instance on the heap 
// and not on the stack.
// On the stack is only the address of the instance.
// So we need to release pSomething before it goes out of scope
// Otherwise the space on the heap will never be freed and there
// is a memory leak
delete pSomething;

compare that with the following:

Code:
Something something;
// Now the entire class instance is on the stack 
// No need to release something before it goes out of scope


Marcel
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top