Smart Recent Blog Post List

Sep 6, 2011

sizeof operator , learning with experiments

sizeof a very interesting operator, lets do some experiments with it to gain more understanding about it.

Lets look at the msdn definition of it first :-
Yields the size of its operand with respect to the size of type char [definition from msdn].

Now lets start experimenting with it :-

what will following statement yields

a) sizeof function ?
        sizeof(&main);
        sizeof(&printf);

b) sizeof an empty class ?
        class A {};
        sizeof(A)

c) Can sizeof return 0 ?

d) What will be the output of following program ?
        int i = 1;
        sizeof(i++);
        cout<<"i="<<i;

e) sizeof following class ?
       class A { char c; int i; };
       sizeof(A)

Now lets look at them one by one

a) sizeof function ?
        sizeof(&main);
        sizeof(&printf);

Answer : sizeof(&main) will return 4 on 32 bit OS.
same hold true for sizeof(&printf). And the reason is very straight forward. As its returning size of function pointer.


b) sizeof an empty class ?
        class A {};
        sizeof(A);
Answer : Its a very interesting question which have very straight forward answer. It directly depends on sizeof operator implementation, if one looks at msdn documentation it says sizeof operator never returns zero. Considering this fact it returns 1.
For more details one can go through link (stroustrup's FAQs):-
                                          http://www2.research.att.com/~bs/bs_faq2.html#sizeof-empty

c) Can sizeof return 0 ?
Answer : NO, sizeof operator never returns 0.


d) What will be the output of following program ?
        int i = 1;
        sizeof(i++);
        cout<<"i="<<i;
Answer : output would be 1, sizeof operator gets resolved at compile time only, no run-time execution will be entertained for sizeof operator. So the output would be 1.


e) sizeof following class ?
        class A { char c; int i; };
        sizeof(A);
Answer : Don't hurry up to reply with 5 byte, because it depends on the byte alignment of class.
If it is 1 byte aligned, output would be 5;
And for 4 byte aligned, output would be 8;




0 comments:

Post a Comment

Smart Recent Blog Post List