Is it possible for the sizeof operator to ever return 0 (zero) in C or C++? If it is possible, is it correct from a standards point of view?
Here's a test, where sizeof yields 0
#include <stdio.h>
void func(int i)
{
int vla[i];
printf ("%u\n",(unsigned)sizeof vla);
}
int main(void)
{
func(0);
return 0;
}
in my view, it is better that sizeof returns 0 for a structure of size 0 (in the spirit of c). but then the programmer has to be careful when he takes the sizeof an empty struct.
but it may cause a problem. when array of such structures is defined, then
&arr[1] == &arr[2] == &arr[0]
which makes them lose their identities.
i guess this doesnt directly answer your question, whether it is possible or not. well that may be possible depending on the compiler. (as said in Michael's answer above).
sizeof
never returns 0
in C and in C++. Every time you see sizeof
evaluating to 0
it is a bug/glitch/extension of a specific compiler that has nothing to do with the language.
struct Empty {
} em;
struct Zero {
Empty a[0];
} zr;
printf("em=%d\n", sizeof(em));
printf("zr=%d\n", sizeof(zr));
Result:
em=1
zr=0