11

AFAIK, the sizeof should not return 0, but the following program:

#include <iostream>

class A {
public:
    int a[0];
};

int main() {
   A obj;
   std::cout << sizeof(obj) << std::endl;
}

outputs 0. Why?

LihO
  • 41,190
  • 11
  • 99
  • 167
  • Why do you expect it not being `0`? – BartoszKP Sep 21 '13 at 19:43
  • 6
    @BartoszKP Because the C++ standard forbids it. – Konrad Rudolph Sep 21 '13 at 19:45
  • 1
    @Dukeling No, the code is illegal C++ anyway. – Konrad Rudolph Sep 21 '13 at 19:52
  • possible duplicate of [Can sizeof return 0 (zero)](http://stackoverflow.com/questions/2632021/can-sizeof-return-0-zero) – BartoszKP Sep 21 '13 at 19:52
  • 1
    @Dukeling In strictly conforming code, yes, the compiler must forbid it. There’s nothing which forbids it as an *extension* to C++, though. I dislike that GCC enables these extensions by default, though. – Konrad Rudolph Sep 21 '13 at 19:56
  • `class B : public A { public: A a; };` zero size class optimization works `sizeof(B)` is 0 – triclosan Sep 21 '13 at 19:57
  • 1
    @triclosan No, that’s not true. The code is still illegal. The zero-size base class optimisation you talk about does exist, but that doesn’t mean that the *derived class’* size can be 0. – Konrad Rudolph Sep 21 '13 at 19:58
  • @KonradRudolph I got it, thanks for clarification blow. My comment was as a joke. – triclosan Sep 21 '13 at 20:00
  • Try this: `A objs[100];` and then tell us what does `sizeof(objs)` return? If it is still zero, then try printing the addresses of two *consecutive* elements, say `objs[0]` and `objs[1]`. Let us know your findings. – Nawaz Sep 21 '13 at 20:03

1 Answers1

13

C++ does not allow zero-sized arrays. A conforming compiler rejects the code, e.g.:

$ g++-4.8 -pedantic-errors main.cpp
main.cpp:5:14: error: ISO C++ forbids zero-size array 'a' [-Wpedantic]
       int a[0];
              ^

So the behaviour of sizeof here is simply not relevant. GCC allows it (without -pedantic) as a compiler extension.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • 1
    +1: This can be found in 8.3.4§1: *"In a declaration `T D [constant-expression]` [..] the constant-expression (5.19) is present, it shall be an integral constant expression and its value shall be greater than zero"*. – Zeta Sep 21 '13 at 19:55
  • What is the size of an object of this class in GCC? I suppose its the size of the pointer. what is it? – hasan Sep 21 '13 at 20:02
  • @hasan There is no point in discussing what a faulty implementation should return in such case. Size of array should not be 0 – BЈовић Sep 21 '13 at 20:04
  • Didn't you say that gcc allow it. – hasan Sep 21 '13 at 20:05
  • so in gcc its not faulty?! – hasan Sep 21 '13 at 20:06
  • What if array have size larger than zero. does pointer have size? or just the array? – hasan Sep 21 '13 at 20:07