# String arguments break optional argument default values? [duplicate]

Following a tip in this post, I use string parameters to label my functions. For example, instead of f[x]:=x^2, I use f["label",x_]:=x^2.

Unfortunately, this strategy breaks the default values for optional arguments, at least when the default value is a global variable.

What should happen:

f[x_,y_:var]:=x+y var=10; f[1] 11 var=20; f[1] 21

What happens when using string parameters as a label:

g["label",x_,y_:var]:=x+y var=10; g["label",1] 11 var=20; g["label",1] 11

It doesn't update to the new value when the global variable is changed. Why not? And more importantly, how can I fix this (without changing my nice labeling scheme, I hope)?

• It behaves exactly the same way, with or without your "label" construct. Hint: Look carefully at what you're doing and the state of var and g as you're doing it, it will be obvious why the example shown exhibits the behavior you observe, and why that behavior is expected and unrelated to your "label" construct. – ciao Mar 8 '20 at 0:21
• Try ClearAll[var]; g["label",x_,y_:var]:=x+y;. (I'd recommend ClearAll[g, var].) – Michael E2 Mar 8 '20 at 0:26
• But I want to be able to change my global variable frequently and have the functions respect the change, without having to use ClearAll or to re-define every function. – WillG Mar 8 '20 at 0:27
• I don't understand the objection to ClearAll -- you're stuck with how Mathematica works. But here's an alternative: Block[{var}, g["label", x_, y_: var] := x + y ] – Michael E2 Mar 8 '20 at 0:46
• Ohhh. Now I see. I thought you were suggesting to use ClearAll between every time I decide to change the value of var. In fact, I just need to use it once to clear var, then re-define the function so that var remains in the function definition, and then the function responds to changes in var. – WillG Mar 8 '20 at 0:50