IMPORTANT: To view this page as Markdown, append `.md` to the URL (e.g. /docs/manual/basics.md). For the complete Mojo documentation index, see llms.txt.
Skip to main content
Version: 1.0.0b1
For the complete Mojo documentation index, see llms.txt. Markdown versions of all pages are available by appending .md to any URL (e.g. /docs/manual/basics.md).

check_bounds

check_bounds[cpu_default: Bool = True](idx: T, size: Int, location: OptionalReg[SourceLocation] = None)

Bounds check which is on by default for CPU, and off by default for GPU.

You can turn off CPU bounds checks for a specific collection by setting check_bounds[cpu_default=False](idx, size, loc), but turn them on for tests with:

mojo build -D ASSERT=all main.mojo

The defaults are optimal for most use cases, where CPU bounds checks are cheap and valuable, but GPU bounds checks are too expensive due to branching costs. For maximum performance you can turn off all asserts regardless of defaults with:

mojo build -D ASSERT=none main.mojo

Parameters:

  • cpu_default (Bool): If the bounds check is on by default on CPU.

Args:

  • idx (T): The index for the bounds check.
  • size (Int): The size of the container, and first index that would be out of range.
  • location (OptionalReg[SourceLocation]): SourceLocation shown on assert error. Defaults to showing the callsite two levels of function calls above this one. So if check_bounds is called inside a __getitem__ method, it will show the source location where the incorrect index was provided.