# Circumventing the default scoping: Assign a variable inside a function [duplicate]

I'm currently trying very hard to assign a variable inside a function.
Therefore I'm using a function like this, which should reassign a predefined variable.

assign[a_] := (HoldForm@a = 2)
a=1;
assign[a]


The problem is that Mathematica uses the value of "a" instead of its name.
Any suggestions?

-

## marked as duplicate by Leonid Shifrin, Oleksandr R., rm -rf♦Jan 13 at 3:40

You should investigate attributes. Specifically, the ones whose names start with Hold. Alternatively you could perhaps use Unevaluated. But, trying to do the assignment as HoldForm[a] = whatever is not valid since HoldForm is Protected. –  Oleksandr R. Jan 13 at 1:35
@LeonidShifrin thanks--I had been looking for a duplicate but didn't succeed in finding it. Actually, I was looking for a different one, but your suggestion is a good match. –  Oleksandr R. Jan 13 at 3:33
@OleksandrR. No problem. This seems to be a common question, you are right - there were at least several related discussions here and on SO - and on MathGroup before that. –  Leonid Shifrin Jan 13 at 4:11

As Oleksandr R. commented, you can do this by setting the appropriate attributes, e.g.

SetAttributes[assign, HoldFirst];

assign[z_] := z = 2

a = 1;
assign[a]
assign[b]

{a, b}

(* {2,2} *)


However, there's a reason for scoping rules and constructs, I'd think long and hard before 'circumventing' them, whatever that may mean in your case.

-