Main BLOGGER
Google
WWW THIS BLOG
Sunday, March 06, 2005
 
Write Code to identify C or C++

#include char xxx;
int main(){
struct xxx {
char c1;
int i;
char c2;
};
printf("in %s the size of xxx is %d\n",
sizeof(xxx)==1?"C":"C++",
sizeof(xxx));
}

rommel:~/puzzle> g++ -o m.o -c C_Cpp.c
rommel:~/puzzle> g++ -o m m.o
rommel:~/puzzle> ./m
in C++ the size of xxx is 12


rommel:~/puzzle> cc -o m1.o -c C_Cpp.c
rommel:~/puzzle> cc -o m1 m1.o
rommel:~/puzzle> ./m1
in C the size of xxx is 1



Another thing we should notice is the size of struct xxx is 12 not 8(2+4+2)! This is because the integers are laid out on four-byte boudaries.

If we change the defintion to

struct xxx {
char c1;
char c2;
int i;
}

the size of struct xxx will be 8!.



<< Home

Powered by Blogger

Google
WWW THIS BLOG