6

I have a template that takes a struct with different values, for example:

struct Something
{
    char str[10];
    int value;
    ...
    ...
};

And inside the function I use the sizeof operator: jump in memory sizeof(Something);

Sometimes I would like to not jump anything at all; I want sizeof to return zero. If I put in an empty struct it will return 1; what can I put in the template to make sizeof return zero?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
hidayat
  • 9,493
  • 13
  • 51
  • 66
  • 5
    Related questions : http://stackoverflow.com/questions/2632021/can-sizeof-return-0-zero and http://stackoverflow.com/questions/2362097/why-is-the-size-of-an-empty-class-in-c-not-zero – Shawn Chin Feb 14 '11 at 15:06

3 Answers3

21

sizeof will never be zero. (Reason: sizeof (T) is the distance between elements in an array of type T[], and the elements are required to have unique addresses).

Maybe you can use templates to make a sizeof replacement, that normally uses sizeof but is specialized for one particular type to give zero.

e.g.

template <typename T>
struct jumpoffset_helper
{
    enum { value = sizeof (T) };
};


template <>
struct jumpoffset_helper<Empty>
{
    enum { value = 0 };
};

#define jumpoffset(T) (jumpoffset_helper<T>::value)
Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
14

What do you think about it?

 #include <iostream>
 struct ZeroMemory {
     int *a[0];
 };
 int main() {
     std::cout << sizeof(ZeroMemory);
 }

Yes, output is 0.

But this code is not standard C++.

  • 2
    yeah, you got me with this: https://stackoverflow.com/questions/47352663/how-can-this-structure-have-sizeof-0/47352751#47352751 – bolov Nov 17 '17 at 14:23
3

No object in C++ may have a 0 size according to the C++ standard. Only base-class subobjects MAY have 0 size but then you can never call sizeof on those. What you want to achieve is inachievable :) or, to put it mathematically, the equation

sizeof x == 0 has no object solution in C++ :)

Armen Tsirunyan
  • 130,161
  • 59
  • 324
  • 434
  • The sizeof an empty struct in C would be 0 though, correct? What's the rationale behind enforcing it to be 1 in the C++ standard? And what's the "1", a mandatory padding byte of unknown value? – Lundin Feb 14 '11 at 15:19
  • because arrays of an empty struct still have to be addressable – jk. Feb 14 '11 at 15:41
  • @lundin: It's not actually necessarily 1 byte. It can be 4 (and on my machine it is) or any other nonegative integer for that matter – Armen Tsirunyan Feb 14 '11 at 15:43
  • 1
    @Lundin: Indeed. I have just experimented with C and C++ (gcc 4.3.2) and the sizeof operator on an empty struct is 0 in C and 1 in C++. – JeremyP Feb 14 '11 at 15:48