Tuesday, November 8, 2011

Type casting secrets


Hello everyone , I would like to share some common type casting secrets things with you. Most of you guys having problem with C/C++ type casting . I hope this post would help you guys to clear your knowledge .
consider the following code
int ival =257;
char   zVal = (char)iVal;

The output would be 1; How come this value . Let me explain .
  binary representation of iVal in memory would be like this  - 00000000 00000000 00000001 00000001
since char consumes 1 byte of memory , first 8 bits will be extracted from iVal . So output is 00000001 =1
sometimes you will get an different result because of machine's architecture . (my one is big endian)

The above example could be shown in following pointer method .
int *ip = new int(257);
char *zVal = (char*)ip;
when you print zVal  (cout <<"Output:"<<(int)*zVal<<endl;) you will get same value that you have received previously . So what is different between both (char*)ip and (char)iVal .  Some might thought when we do a pointer casting 4 bytes memory will be extracted ..:) Actually that is wrong .  Pointer casting converts data types in to pointer .

we will dig further in casting .
struct A
{
  int a ;
  int b ;
};
 struct B
{
  int c;
};

int main()
{
   A aa;
aa.a =100;
aa.b = 200;

B bb = (B)aa;    // Error . this casting is not allowed in C/C++

B *bb = (B*)&aa   // This is fine .

A *pa = new A;
pa->a =100;
pa->b= 200;

B *pb = (B*)pa;  // this is will work fine .
}


So we can cast both way in C/C++ which means we can cast any data type .


When you declare STRUCT_A it is declared into memory:
|A|A|?|?|
Since it contains two integer it takes up one block of memory(hypothetically)

When you declare STRUCT_B it is declared into memory:
|B|?|?|?|
With one integers it takes up two blocks.

If you do (STRUCT_A)struct_b;
only the first two block of B is going to be read since STRUCT_A only takes two block of memory.

if you (STRUCT_B)struct_a;
the int in STRUCT_A will be read, along with who know what in the next block of memory since STRUCT_B calls for one blocks of memory.

In C++ we can find more about casting . We will discuss about that later . ..:)



1 comment:

  1. struct A
    {
    int a ;
    int b;
    int c;

    };

    struct B
    {
    int e;
    char d;

    };

    A *a = new A;
    a->a=999;
    a->b= 102;
    a->c = 104;


    B *pb= (B*)a;
    The output of pb->e is f why? surprised ! you might think size of B is 5 bytes . But compiler do alignment here . eventhough char is 1 byte . 4 bytes of memory will be occupied and 1 bye of memory will be used . other 2 bytes of memory will be having holes . (wasted memory ) that is why we are getting f(ASCII) value..:)

    ReplyDelete