How To Watch A Variable Even After Its Scope Is Over

January 19, 2009

Noramally, the value of a variable declared in a function can be seen in the watch window only when the control is inside that function itself (eg. When the above function calles a new function and if we step into the new function.) . Let’s discuss an example.

void SomeFunction()
   int myVariable = 20;
int main()
   int myVariable = 10;
   return 0;   

In the above example, if I put a break point in the function main after the statement int myVariable = 10; I can see the value of myVariable in the watch window as follows.


Now, if I put another break point in SomeFunction() after the statement int myVariable = 20;, when th execution flow reaches there, the watch window will show the value of myariable as 20 only.

So we have lost the value of myVariable declared in main(), eventhogh it lifetime is not over now.

How To Add a Permanent watch

We can still view the value of myVariable declared in main() inside the function SomeFunction(). For this, we will use the address of memory location (rather than the variable name) in which myVariable has been declared in main(). We can view the contents of this memory location as long as it has life in the program.

When the control reaches the break point in main(), take the address of myVariable using the & operator. Now we have a valid memory location address (a pointer). Still, it can be a raw pointer. So cast it to the correct type (int, in this case, as myVariable is of type integer) as

(int*)(address of myVariable)

adding-a-watch1Now see how the watch window shows the value we have stored, when the control reaches the second break point.