r/cprogramming • • Oct 23 '26

Technically speaking, are we supposed to only index arrays using size_t?

Is this technically the best way to index an array?

for (size_t i = 0; i < sizeof(a); i++)

{

a[i];

}

This makes sure that any array size, across all machines can be indexed?

22 Upvotes

66 comments sorted by

View all comments

Show parent comment

2

u/Zirias_FreeBSD Oct 23 '26

Obviously requires a signed type as written ... (and should probably start at N-1 then). There are also alternatives to avoid the unsigned underflow (like do ... while, or the admittedly slightly obfuscated for (<type> i = N; i--;)). I don't really care too much right now and have no idea what I'd use (in case an int doesn't fit the bill).