C/C++'s Row-Major: Driven by Array Syntax & Reading Order

C and C++ adopted row-major order largely due to their array declaration syntax (e.g., `array[rows][cols]`) where the last index varies fastest. This naturally stores elements of a row contiguously in memory, aligning with the common left-to-right, top-to-bottom reading order.

The top 3

  1. C's Row-Major: Pointer Arithmetic's Foundation: C's design favors row-major order due to its close ties with pointer arithmetic, where `arr[i][j]` is directly mapped to `*(arr + i * num_cols + j)`. This simplifies memory addressing and makes row-wise access efficient through contiguous memory blocks.
  2. Fortran vs. C: Indexing's Memory Layout Divide: Fortran's `(row, column)` array indexing often leads to column-major memory storage, where elements of a column are contiguous. In contrast, C/C++'s `[row][column]` syntax naturally maps to row-major order, aligning with how rows are stored contiguously.
  3. Top 3 Coding Practices for C/C++ Row-Major Performance: Optimize C/C++ matrix operations by iterating innermost through columns (`j` loop inside `i` loop), using contiguous 1D arrays for 2D data, and avoiding large strides in memory access to maximize cache hits.

Sources

Open the full topic