How use break in loop if ? ERROR: syntax: break or continue outside loop

julia> if 1>0 println("Stop") ;break
       else println("Go")
       end
ERROR: syntax: break or continue outside loop

Thanks
Paul

An if statement is not a loop. for and while statements are loops and can be used with break and continue.

1 Like

Yes, but 1.st loop run and run

while true
println(1)
     while 1>0 println("Stop"); break
     end
println(2)
end
1
Stop
2
1
Stop
2
1
Stop
...

I need to break 1.st lopp ! like this :

while true
println(1)
     if 1>0 println("Stop"); break
     end
println(2)
end
1
Stop

julia>
1 Like

You can use short-circuit evaluation, this works:

while true
    println(1)
    1>0 && begin
        println("stop") 
        break
    end
println(2)
end

If you need to break it like that I suggest you do exactly that. The error in your original post happens if you try to run the if and break in isolation without the while loop context, which isn’t a meaningful thing to do.

1 Like

but, but, but… How to break loop for without while inside?

for i=1:10
println(1)
do somethink
     if 1>0 println("Stop"); break
     end
println(2)
do more...
end

Just like you wrote:

julia> for i=1:10
       println(1)
       #do somethink
            if 1>0 println("Stop"); break
            end
       println(2)
       #do more...
       end
1
Stop

Or do you want

       println(1)
       #do somethink
            if 1>0 println("Stop"); continue
            end
       println(2)
       #do more...
       end
1
Stop
1
Stop
1
Stop
1
Stop
1
Stop
1
Stop
1
Stop
1
Stop
1
Stop
1
Stop
1 Like