1

Consider a generic expression myvar which is not yet initialized to any value. If we want to create a reference (pointer) to myvar, we can simply set:

pointToMyvar = myvar;

Now if we go ahead and initialize myvar to some value:

myvar = 5;

we see that our pointer properly accesses the correct memory location to retrieve the value:

pointToMyvar

5

And, of course after myvar is changed again

myvar = 7;

the pointer knows about it

pointToMyvar

7

However, now that myvar is initialized, it seems that we cannot create any further pointers to it. If we now try

pointToMyvarAgain = myvar;

and change myvar yet again

myvar = 10;

we see that the new reference does not actually refer to myvar but rather just to the integer that was stored in myvar at the moment of assignment:

pointToMyvarAgain

7

Therefore, I would like to know if there is any way how I could define a pointer to myvar (same as pointToMyvar above), after myvar has been initialized to some explicit value? Thanks for any suggestion!

Kagaratsch
  • 11,955
  • 4
  • 25
  • 72

1 Answers1

4

This is one those times when it is important understand the difference between Set and SetDelayed. You can get the behavior you are looking for with SetDelayed, although you should be aware that you are not creating a pointer. The Wolfram Language does not support pointers as such.

pointToMyvar := myvar
myvar = 5;
pointToMyvarAgain := myvar

{pointToMyvar, pointToMyvarAgain}

So far everything looks the as it did when Set was used for all assignments. But now:

myvar = 42;
{pointToMyvar, pointToMyvarAgain}

{42, 42}

So with SetDelayed, it does matter whether or not myvar has a value when the assignment is made. Examining the definition of pointToMyvarAgain in the kernel

Definition @ pointToMyvarAgain

shows

pointToMyvarAgain := myvar

Because myvar is stored in the definition unevaluated, it appears to act as pointer.

Also see Understand the difference between Set (or =) and SetDelayed (or :=)

m_goldberg
  • 107,779
  • 16
  • 103
  • 257