Can sizeof return 0 (zero)

后端 未结 10 1569
爱一瞬间的悲伤
爱一瞬间的悲伤 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:53

    typedef struct {
      int : 0;
    } x;
    
    x x1;
    x x2;
    

    Under MSVC 2010 (/Za /Wall):

    sizeof(x) == 4
    &x1 != &x2
    

    Under GCC (-ansi -pedantic -Wall) :

    sizeof(x) == 0
    &x1 != &x2
    

    i.e. Even though under GCC it has zero size, instances of the struct have distinct addresses.

    ANSI C (C89 and C99 - I haven't looked at C++) says "It shall be possible to express the address of each individual byte of an object uniquely." This seems ambiguous in the case of a zero-sized object, since it arguably has no bytes.

    Edit: "A bit-field declaration with no declarator, but only a colon and a width, indicates an unnamed bit-field. As a special case of this, a bit-field with a width of 0 indicates that no further bit-field is to be packed into the unit in which the previous bit-field, if any, was placed."

提交回复
热议问题