Can sizeof return 0 (zero)

后端 未结 10 1541
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-28 08:14

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?

相关标签:
10条回答
  • 2020-11-28 08:58

    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;
    }
    
    0 讨论(0)
  • 2020-11-28 09:04

    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).

    0 讨论(0)
  • 2020-11-28 09:06

    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.

    0 讨论(0)
  • 2020-11-28 09:10
    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
    
    0 讨论(0)
提交回复
热议问题