Scoping variable inside if and unsafe warning

Consider the following code:

a = "abcd"
if true do
  a = "ijk"
 f = fn() ->
   a = "fn"
 IO.puts a

In this example, a will be printed as ijk. Elixir also gives the following warning: warning: the variable "a" is unsafe as it has been set inside a case/cond/receive/if/&&/||. Please explicitly return the variable value instead.

I know Elixir is lexically scoped. That’s why the anonymous function could not change the value of a in the outer scope. But the question is how come it is changing inside the if block? And why Elixir gives an unsafe warning?

I think it is something to do with if being a macro. But I am not able to explain it properly. Any help to understand this better would be appreciated.

1 Like

Old holdover from older Elixir days where variables in if blocks could change variables outside of them. This mis-feature is currently deprecated, hence why you are seeing the warning, because soon this mis-feature will be removed and scoping will work correctly. :slight_smile: