Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is sizeof(something) == 0?

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?

like image 507
hidayat Avatar asked Feb 14 '11 15:02

hidayat


2 Answers

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)
like image 52
Ben Voigt Avatar answered Nov 04 '22 11:11

Ben Voigt


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++.

like image 36
Константин Гудков Avatar answered Nov 04 '22 10:11

Константин Гудков