How to avoid using global variable in "for loop" inside a function?

I have two questions please:
1- Are r, s global or local variables in the below main code?

function ss(r, s)
u =r+s;
a =r*s;
return u, a
end

#main code
r=5;
s=9;
q,w = ss(r, s)

2- How to get ride of defining iter as a global variable inside for loop in the pp function?

function pp()
iter=0;
for i in 1:10
global iter +=1;
end
end
  1. When you pass them as parameters, they will be in the scope of the function (always do that). That is: they are global in the “main code”, but when you pass them as parameters to the function they are local to the function. The function will specialize for their type, and all is good there.

  2. In this case it should work without the global. If you do not want to initialize it, use local iter:

i. e. something like:

function pp()
    local iter
    for i in 1:10
        iter =i
    end
    return iter
end

So in the blow code, r, s are being passed as parameters, aren’t they!

function ss(r, s)
u =r+s;
a =r*s;
return u, a
end

#main code
r=5;
s=9;
q,w = ss(r, s)

Actually I want to initialize because the iteration range is different. and Sorry I was asking if there is no function, i.e., I just want to run the below code

    iter = 0
    for i in 1:10
        global iter +=1
    end

Yes, that code is perfectly fine. You have created r and s in the global scope, but you have passed them as parameters to the function. That is how things should be done.

Perfect, that is how it is done. (you can also do for i in 0:9, of course, if you are not using that counter for anything else).

You should avoid that if you want any performance. The scoping rules in that case are a little bit tricky. Read this: Scope of loops · JuliaNotes.jl

This is because I have a main code which I put at its early beginning all the modules and packages. This code has the main for loop which has that iter variable which I need to get ride off being global.

The variable will be global if you are in the global scope. What you mean exactly?

So, the global scope is the same as in the main code, right? I mean since iter is in the main code(global scope), then defining iter as global in the for loop won’t change anything in the performance, right?

#main code
#dowork()
iter = 0
    for i in 1:10
        global iter +=1
    end

You are forced to declare it global (unless you type that in the REPL), otherwise you will get an error.

Performance will suffer, as iter is a global non-constant variable.

1 Like

Thank you very much for your explanations!

1 Like