How to use @inbounds?

julia> f(x,y) = sqrt( x^2 + y^2 );

julia> xset= 10:11; yset= 12:13; i= 1;

julia> m= Matrix{Float64}(undef, length(xset)*length(yset), 3); size(m)

julia> for x in xset
           for y in yset
                global i
                m[i,:]=        [ x, y, f(x,y) ]
            end#for x

julia> m
4×3 Array{Float64,2}:
 10.0  12.0  15.6205
 10.0  13.0  16.4012
 11.0  12.0  16.2788
 11.0  13.0  17.0294

so I have code that does not trigger an exception. Now I want to try out @inbounds. I repeat the same, sticking @inbounds in front of either for or the m[i,:]. This gives me a

ERROR: BoundsError: attempt to access 4×3 Array{Float64,2} at index [5, Base.Slice(Base.OneTo(3))]

I understand that I can write different code, but why does this trigger an exception trying to index a fifth element?? and why would this not trigger an error without @inbounds? I am probably misunderstanding @inbounds altogether. I thought it only told the compiler not to bother range-checking, and because I had no error before, it should still be ok now with the same work.



This actually doesn’t have anything to do with @inbounds. You’re using a global counter i and it’s continuing to increment when you run the loop a second time.

As for why the error is thrown: @inbounds allows the compiler to omit bounds checks but does not require it to do so. In particular, I don’t think it currently has any effect when your code is not inside a function (as is the case in your example).