15

I'm reading "King K.N's C programming" and found the following statement:

We discussed using the expression sizeof(a)/sizeof(a[0]) to calculate the number of elements in an array. The expression sizeof(a)/sizeof(t), where t is the type of a's elements, would also work, but it is considered an inferior technique.

Why is it considered an inferior technique?

  • 8
    did you consider what would happen if programmer changes type of elements in a? to a type having different size than t. First expression will still be okay, while second will break – gnat Jul 6 '15 at 21:46
  • 1
    @gnat: You should make that an answer. – Martin York Jul 7 '15 at 0:30
26

sizeof(a)/sizeof(t) explicitly codes the type into the expression. You now have the type specified in multiple locations, with no compiler support for ensuring that you're using the same type. So, if you change the base type of the array, but not in the (completely separate) count expression, bingo: your code will compile just fine, but your element count will be wrong. If you're lucky your program will crash, but if not it will function almost completely correctly, but every once in a while will behave totally bizarrely.

sizeof(a)/sizeof(a[0]) is guaranteed to be correct, only requiring the name of the array. Change the type and you're fine; change the array name and the compiler will complain. No thinking required: we like that kind of programming.

  • Well, I really prefer sizeof a/sizeof*a, even though it's not really a substantial difference. – Deduplicator Jul 20 '15 at 16:00

Not the answer you're looking for? Browse other questions tagged or ask your own question.