Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

function variable does not live outside a for loop

Tags:

julia

I have a generic function in julia that the aim is to say if a member of a vector of a given dimension is negative or not. After a few variations I have:

function any(vec)
    dim = size(vec)
    for i in 1:dim[2]
        fflag = vec[1,i] < 0 
        println("Inside any, fflag = ", fflag)
        if fflag == true
            result = 0
            println("blabla ", result)
            break
        else
            result =1
            println("blabla ", result)
            continue
        end
    end
    println("hey, what is result? ")
    println(result)
    return result
end

If I run a test I found the following result:

Inside any, fflag = false
blabla 1
Inside any, fflag = false
blabla 1
Inside any, fflag = false
blabla 1
hey, what is result? 

result not defined
at In[7]:57

I don't know why the compiler says me that 'result' is not defined. I know the variable exist but why does not live outside the for loop?

like image 474
user2820579 Avatar asked Apr 01 '14 22:04

user2820579


People also ask

Can you access a variable outside of a for loop?

If the variable is declared outside the loop, then it has the global scope as it can be used through-out the function and inside of the loop too. If the variable is declared inside the loop, then the scope is only valid inside the loop and if used outside the loop will give an error.

Can functions use variables outside?

In Python and most programming languages, variables declared outside a function are known as global variables. You can access such variables inside and outside of a function, as they have global scope.

Should you declare variables inside or outside a loop?

In terms of readability and maintainability you should prefer to define the variable inside the loop.

Can you put a for loop inside a variable?

Often the variable that controls a for loop is needed only for the purposes of the loop and is not used elsewhere. When this is the case, it is possible to declare the variable inside the initialization portion of the for.


1 Answers

The documentation on variable scoping clearly states that a for loop defines a new scope. This means result is going out of scope when execution leaves the for loop. Hence it is undefined when you call println(result)

Defining result in advance of the for loop should give the behaviour you are expecting:

function any(vec)
    dim = size(vec)
    result = -1
    for i in 1:dim[2]
       ...

Or if you do not wish to assign a default value, and are sure the for loop will set its value, you can do:

function any(vec)
    dim = size(vec)
    local result
    for i in 1:dim[2]
       ...

In the first example, if the for loop does not set a value, result will be -1.

In the the second example, not setting a value in the for loop will leave result undefined.

like image 190
PeterSW Avatar answered Oct 19 '22 14:10

PeterSW