Tuesday, February 12, 2013

Size of empty structure and empty class

#include <stdio.h>

class A
{

};


struct ST
{

};

int main()
{
   A a;

   printf("Size of Empty class: %d byte", sizeof(a));

   ST stvar;

   printf("Size of Empty structure: %d byte", sizeof(stvar));
  
   return 0;
}

O/P:-
Size of Empty class: 1 byte
Size of Empty structure: 1 byte

Explanation:
There's no content. It's just a dummy byte.
Every class or struct must have its sizeof greater than 0, ergo your behavior.
It's expected and mandated by the standard.

For More Information: click here

***********************************************************************************

#include <stdio.h>
class Empty
{

};

class TwoEmpties
{
   Empty a;
   Empty b;
};

int main()
{
    TwoEmpties te;
    printf("Size: %d bytes", sizeof(te));
    return 0;
}

O/P:
Size: 2 bytes

***********************************************************************************

#include <stdio.h>
class Empty
{
   int i;
};

class TwoEmpties
{
   Empty a;
   Empty b;
};

int main()
{
    TwoEmpties te;
    printf("%d", sizeof(te));

    return 0;
}


O/P:
Size: 8 bytes


No comments:

Post a Comment