Wednesday, May 2, 2007

goto and static.

I don't want nothing much to write here except the following code sequence.Can anyone predict the outout???

int _tmain(int argc, _TCHAR* argv[])

{

goto XXX;

static int u = 90;


XXX:

printf("%d",u);

return 0;

}


It is 90 , that is the variable u getting the value 90. How the u gets this value ? .Eventough there is a goto before the assignent statement.

If you debug the following code you can see that the control never goes to the line "static test u = 90;" .Oho god how this happens???.

I think the compiler will handle the static variables while on the program loading. Because compiler need to reserve memory for a static variable whether it is declared in local function or global , it doesn't matter. Thats how here the variable u gets the value 90. if it is not a static variable the the program crashes without asking anybody.


If you try the same code replacing integer u with a some class object , like



class test
{


public :
  int val;
  test() 
  {
    val = 90;
   }


};




int _tmain(int argc, _TCHAR* argv[])
{

goto XXX;
static test u;
XXX:
printf("%d",u.val);


return 0;

}


you will never get the value 90 as output. Because the construcor is not called by the compiler eventhough it is static object.


So summarizing the facts , it will be like this.


1. static varibles memory allocation happens in anycase.
2. compiler also saves the value to the varible in statement like static int s = 90;
3 If you have class and it has a constructor accepting an integer , you can write like

static MyClass obj = 90; (But it will not get called ever, in our case)

Any comments , welcome!!!.

Note : I have tried the above test with VS2005 only. This behavior is compiler dependent.


No comments: