Gotchas: Difference between revisions

m
Line 187:
 
The gotcha is that <code>sizeof</code> can't be used to calculate anything at runtime. The <code>sizeof</code> operator merely provides a compile-time constant using the information you provided to the compiler about that variable. For arrays, the data type of the array and the number of elements are multiplied together to give the size. C uses this information to know how many bytes to reserve on the stack for the array, but the size isn't stored anywhere with the array. As far as the CPU knows, the fact that the above function's return value is the size of the array is merely a coincidence.
 
 
Put another way, <code>sizeof</code> is just a <code>#define</code> that doesn't pollute your namespace:
Line 196 ⟶ 197:
return size_of_bar;
}</syntaxhighlight>
 
 
 
As a result of this subtle nuance, many new C programmers will write the code below thinking that it will return a value corresponding to the number of elements the array was originally declared with.
1,489

edits