Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top