Main BLOGGER
Google
WWW THIS BLOG
Tuesday, March 29, 2005
 
Something about C


In C/C++, the memory layout of struct is aligned to integer.
For example
struct xxx { char c1; int i1; char c2; }
struct yyy { char c1; char c2; int i1; }
have different size.
sizeof(xxx)==12 while sizeof(yyy)==8

In C, struct xxx only declares a name, so sizeof(xxx)=1
In C++, struct xxx defines a variable, so sizeof(xxx)=12

This feature can be used to distinguish C and C++ at runtime

#include
char xxx;
char yyy;
int main()
{
struct xxx {
char c;
int i1;
char c2;
};

struct yyy {
int i1;
char c;
char c2;
};

printf("size of xxx = %d\n",sizeof(xxx));
printf("size of yyy = %d\n",sizeof(yyy));
printf("compiled by %s\n", sizeof(xxx)==1?"C":"C++");
}




<< Home

Powered by Blogger

Google
WWW THIS BLOG