Skip to content

Square Brackets in C

In C, square brackets ([]) are a shorthand notation for pointer arithmetic. For example, a[i] is the same as *(a + i), which means that you can use i[a] instead, since addition is commutative.

Perhaps you are wondering in what situation i[a] would be preferred over a[i]. Well, in the Chromium project 1, the notation of 0[x] is used to get the length of a C array:

#define COUNT_OF(x) (sizeof(x)/sizeof(0[x]))

The 0[x] notation here prevents the misuse of COUNT_OF on C++ types that overloads operator[]().

When I shared this with my friend, he asked me in what situation would COUNT_OF(x) be used, given that the size of C arrays is known at compile time. (except for Variable Length Arrays (VLAs), which are typically not used in production code)

I searched the Chromium codebase 2 and found that COUNT_OF(x) is used to determine the size of arrays that are initialized from brace-enclosed lists:

int x[] = {1,2,3};

Comments