In the programming languages C and C++, the unary operator 'sizeof' is used to calculate the sizes of datatypes. sizeof can be applied to all datatypes, be they primitive types such as the integer and floating-point types defined in the language, pointers to memory addresses, or the compound datatypes (unions, structs, or C++ classes) defined by the programmer. sizeof is a compile-time operator that returns the size in bytes of the variable or parenthesized type-specifier that it precedes. -- http://en.wikipedia.org/wiki/Sizeof --
Here is an interesting test for the size of several types by myself.
#include "stdio.h"
#define mySizeOf(x) ((char*)(&(x)+1)-(char*)(&x))
struct myType { // This is a structure containing four variables of different types
char a;
int b;
float c;
double d;
};
struct blankType { // This is a structure with no variable
};
class CBlankClass { // This is a class with no member variable
public:
public:
CBlankClass() {};
~CBlankClass() {};
void function1() {};
void function2() {};
};
class CMyClass { // This is a class with a int type member variable
public:
int memberVar1;
public:
CMyClass() {};
~CMyClass() {};
void function1() {};
void function2() {};
};
void main()
{
char var1;
printf("Size of char type = %d\n", mySizeOf(var1));
int var2;
printf("Size of int type = %d\n", mySizeOf(var2));
float var3;
printf("Size of float type = %d\n", mySizeOf(var3));
double var4;
printf("Size of double type = %d\n", mySizeOf(var4));
char var5[] = "AB";
printf("Size of char array ""AB"" = %d\n", mySizeOf(var5));
struct myType var6;
printf("Size of struct myType = %d\n", mySizeOf(var6));
struct blankType var7;
printf("Size of struct blankType = %d\n", mySizeOf(var7));
CBlankClass var8;
printf("Size of class CBlankClass = %d\n", mySizeOf(var8));
CMyClass var9;
printf("Size of class CMyClass = %d\n", mySizeOf(var9));
}
Output:
Size of char type = 1
Size of int type = 4
Size of float type = 4
Size of double type = 8
Size of char array AB = 3
Size of struct myType = 24
Size of struct blankType = 1
Size of class CBlankClass = 1
Size of class CMyClass = 4
From this result, interesting things are these,
Size of struct myType = 24
--> For a struct myType, if it has only "char a", its size is 1. But, if it has "char a" and "int b", its size becomes not 5 but 8. If it has "char a", "int b", and "float c", its size becomes 12.
Size of struct blankType = 1
Size of class CBlankClass = 1
--> Both black structure and class (no member variable) have its size 1.
--> For class, member functions don't affect on the size.
Size of class CMyClass = 4
--> If a class has member variables, its size will be the same to the situation of structre above.
No comments:
Post a Comment