Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is object global null or not?

I have a code which is shown below. I was asked in an interview

object global;
void f()
{
  object local=new object();
  global=local;
}

He asked, "Is global null outside the function?". Since the local variable loses its scope outside the function and its reference is given to global it should also be null but it isn't why?

like image 994
Prabhavith Avatar asked Jun 28 '26 00:06

Prabhavith


1 Answers

You have to differentiate between variables and values.

The local variable only exists inside the function, but that doesn't mean that the value that the variable contains doesn't exist outside the function.

When you assign the value of local to global, you are copying the reference to the object so that there are two reference to the same object. The local variable goes away when you leave the function, but the value that you copied to the global variable still exists, and the object survives as there is still a reference to it.

like image 75
Guffa Avatar answered Jun 29 '26 12:06

Guffa