Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

size of class with empty array in C++

Tags:

c++

class

sizeof

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?

like image 874
Raunak Chowdhury Avatar asked Sep 21 '13 19:09

Raunak Chowdhury


1 Answers

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.

like image 61
Konrad Rudolph Avatar answered Sep 30 '22 20:09

Konrad Rudolph