# How to use @inbounds?

**URL:** <https://discourse.julialang.org/t/how-to-use-inbounds/19048>\
**Category:** Performance\
**Created:** [December 28, 2018, 2:13am UTC](https://discourse.julialang.org/t/how-to-use-inbounds/19048 "2018-12-28T02:13:12Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![iwelch](https://avatars.discourse-cdn.com/v4/letter/i/8c91f0/32.png) [@iwelch](https://discourse.julialang.org/u/iwelch)\
**Post date:** [December 28, 2018, 2:13am UTC](https://discourse.julialang.org/t/how-to-use-inbounds/19048/1 "2018-12-28T02:13:12Z")

</div>

```julia
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)
(4,3)

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

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

```julia
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.

/iaw

---

<div class="post-metadata">

**Author:** ![rdeits](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/rdeits/32/286_2.png) [@rdeits](https://discourse.julialang.org/u/rdeits)\
**Post date:** [December 28, 2018, 2:21am UTC](https://discourse.julialang.org/t/how-to-use-inbounds/19048/2 "2018-12-28T02:21:52Z")

</div>

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).

---

<div class="post-metadata">

**Author:** ![iwelch](https://avatars.discourse-cdn.com/v4/letter/i/8c91f0/32.png) [@iwelch](https://discourse.julialang.org/u/iwelch)\
**Post date:** [December 28, 2018, 2:29am UTC](https://discourse.julialang.org/t/how-to-use-inbounds/19048/3 "2018-12-28T02:29:29Z")

</div>

embarrassing…
