Function variable not out of for loop

I have a common function in julia whose purpose is to tell whether a vector element is a given size negative or not. After several options, I:

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 ran the 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 do not know why the compiler tells me that the "result" is not defined. I know that a variable exists, but why doesn’t it live outside the for loop?

+4
source share
1 answer

The documentation in the scope of variables clearly indicates that the for loop defines a new scope. This means that it resultgoes beyond when execution leaves a for loop. Hence it is undefined when you callprintln(result)

result for , :

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

, for , :

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

, for , result -1.

, for, result undefined.

+8

Source: https://habr.com/ru/post/1534547/


All Articles