Search code examples
c++sizeof

Why the size of the object is zero


I am getting the sizeof of object as zero, which is ought not to be. Please explain me the concept as why the compiler is giving this answer?

  #include<iostream>
  using namespace std;

  class xxx{
      public: int a[];  // Why this line is not giving error.
  }; 

  int main(int argc, char *argv[])
  {
      xxx x1;
      cout<<sizeof(x1); //Q=Why this code is not giving error.
      return 0;
  }

Solution

  • As the others have said, an object in C++ can never have size 0.

    However, since the code isn’t valid C++ in the first place (arrays cannot be empty) this is inconsequential. The compiler just does what it wants.

    GCC with -pedantic rejects this code. MSVC at least warns. My version of clang++ with -pedantic ICEs but does emit a warning before that.