I'm reading King K.N's C programming and I'm reading 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 it is considered inferior technique?
Why using sizeof of type to calculate the number of elements in an array is considered inferior to using sizeof of an element?
c;array
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 count expression, bingo: your element count is wrong. If you're lucky your program will crash, but if not it will function almost completely fine, 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.