Click here to Skip to main content
15,889,651 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have declared a variable as int x and i compiled the program and when i delete this variable from the program and after compilation i again redeclare the same variable as int x, then will the address be same for this variable in the memory during redeclaration?and if the address changes ,why is it?
Posted
Updated 8-Aug-11 6:14am
v2
Comments
Fredrik Bornander 8-Aug-11 12:08pm    
Is x a class or struct member, a global variable or a function local variable or a function argument variable?
Ashutosh_g 8-Aug-11 12:09pm    
it is a local variable in main() function..
Richard MacCutchan 8-Aug-11 13:53pm    
1. Maybe, it depends on the compiler.
2. Why does it matter?
YvesDaoust 9-Aug-11 2:33am    
@TRK3: very well observed! But oooops, sorry, I deleted the Solution and your comment by accident and don't know how to undelete :(

A linker allocates addresses or offsets based on the order it finds it in the symbol table.
It has got nothing to do with the name of the variable.
So using the same name to re-declare a variable does not guarantee the same address that was previously allocated.
 
Share this answer
 
Comments
John R. Shaw 8-Aug-11 23:41pm    
5 - Good answer. If nothing else has changed, then it will probably be the same address. But, like you said, there is no guarantee.
// Stack address: 0000100
for(int i=0;i<10;i++){ /*something */ } // Stack address: 00000FC

// Stack address: 0000100
// do anything else

for(int i=0;i<10;i++){ /*something */ } // Stack address: 00000FC

// Stack address: 0000100

You can see - the program reuses the same address on the stack.
Or in another way
void function(int x,int y)
{
  if(1==x)
  {
    int  a;
    // do...
  }
  if(1==y)
  {
    int  z; // <- 'z' uses the same adress as 'a' before
  }
}

Regards.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900