# Setting the value of a global variable from inside a function

I am trying to set the value of a global variable X from inside a function.

I want the value of this variable to change when the function is called. The function will also return the string "pass" when called.

Here is the code:

function[] := (
X = 10;
Return["pass"];
);


However, when I set a new value for X in the function, then call the function

function[]


and then call X, I get the OLD value of X, implying that X was never changed.

How would I go about doing this?

• I can't reproduce the problem. – andre314 Feb 29 '20 at 23:45
• I suggest you restart the kernel and try again. – andre314 Feb 29 '20 at 23:46
• You must reevaluate the definition of the function. That said, changing a global from a local context (the function) in this way is just not good practice. – ciao Feb 29 '20 at 23:46
• To analyse the problem you can evaluate ??function and see if there is something abnormal. You can paste screenshot in the question above too. – andre314 Feb 29 '20 at 23:50

Evaluate this in a new session with a clean notebook.

x = 42;
function[] := (
x = 10;
"pass"
)


Note that you do not need to use Return. A Wolfram Language function always returns the last expression it evaluates.

Evaluate

Dynamic[x]


You should get the output 42, the current value of x. Now evaluate

function[]


You should get the output pass and the output below Dynamic[x] should change to 10. Dynamic is very useful for tracking the changes to global variables when debugging.