On 20 Apr 2007 15:33:36 -0700, skibud2 <mi***********@ gmail.comwrote
in comp.lang.c:
Consider this example:
u8 my_array[10];
for (i = 0; i < (sizeof(my_arra y)/sizeof(u8)); i++) {
...
}
In the standard C specification, is the evaluation of
'(sizeof(my_arr ay)/sizeof(u8))' to 10 guarenteed to happen at compile
time? Or is it a compiler optimization? From what I have read, it
looks like it is a compiler optimization, but I would like to get
confirmation.
Now if is not guarenteed to happen at compile time, is it better to do
something like the following:
const u8 my_array_size = (sizeof(my_arra y)/sizeof(u8));
I wouldn't do this, C is not C++. If you define this at file scope,
it has external linkage and the compiler must actually create the
object, because it cannot tell whether another translation unit will
refer to it by name.
Even if you define it as static, some C compilers will create the
object and read its value when you use it in an expression.
to guarentee that you are not doing a divide a run time? On the
systems I have worked on, divides take a very long time. However,
almost every compiler that I have dealt with does the evaluation at
compile time.
Despite what others have said, the C language standard does not
require a compiler to evaluate constant expressions at compile time
unless it needs to use the value at compile time, as in Ian's example
of using it to define the size of an array.
Another such case would be where an integer constant is used as a case
value in a switch statement.
In this particular case, it makes much more sense to define the value
ahead of time and use it both for defining the array and when you need
the number of its elements:
#define MY_ARRAY_SIZE /* some value */
u8 my_array [MY_ARRAY_SIZE];
In the general case, you are better off using a nameless enum, so long
as the value fits in the range of an int:
enum { my_array_size = sizeof my_array / sizeof *my_array };
This will be evaluated at compile time and not create an object at run
time.
Also note that in general, the expression for the number of elements
should make use of the explicit conversion of an array name to a
pointer, and using that to access the type of the members:
elements = sizeof array_name / sizeof *array_name;
If you ever decide that you need to change the type, say to int or
long, you don't have to hunt down and make sure you change all the
sizeof expressions.
--
Jack Klein
Home:
http://JK-Technology.Com
FAQs for
comp.lang.c
http://c-faq.com/
comp.lang.c++
http://www.parashift.com/c++-faq-lite/
alt.comp.lang.l earn.c-c++
http://www.club.cc.cmu.edu/~ajo/docs/FAQ-acllc.html