Sunday, 3 April 2016

Typecasting C/C++ Brush up

WHEN SOME BIG SPACE DATA TRY TO INSERT IN SMALL SPACE DATATYPE THERE OCCUR'S AN ERROR SO TO REMOVE THAT ERROR WE DO TYPE CASTING.

suppose you have two datatypes let say
int a=2;                      [2 byte]  (int a=300 will be stored in meom as 00101100 00000001
float b=3.2;                [4 byte]

Now in case you write an instruction

a=b;          i.e [2 byte]<--[4 byte] then it will give error

so, for that you need to type cast above 4 byte float data type into int

i.e a=(int)b;    Now it will not give any error

Let's Here only discus the Meomory allocation in array How data will store in
int a[5]={300,301,302,20,40}

300=00000001  00101100 but in meomory  first LSB is stored then MSB
similarly 301= 00000001 00101101
i.e as 00101100 00000001  and then for 301..302..20..40


further

let i have
int a[5]={300,301,302,20,40};
int *b;
int *b=a ; /  int *b=&a;   ----OK NO ERROR
char*c;
(char*)c=a; <--NO ERROR IT WILL GIVE U ONLY 1 BYTE FROM INT.
*c=a;  ---ERROR   [1byte]<--[2byte]
*c=(char*)a;---OK,NO ERROR

float *d;
*d=a; [4 byte]<--[2byte] Ok, NO ERROR.

in arithmatic typecasting is done automatically

  1. #incude <stdio.h>
  2. #include <conio.h>

  3. int main()
  4. {
  5.     int a=20;
  6.     char k;
  7.     printf("type casted k=(char)a ");
  8.     k=(char)a;
  9.     printf("the value of k=%c\n",k);
  10.     printf("type casted a=k ");
  11.     k='a';
  12.     a=k;
  13.     printf("the value of a=%c\n",(char)a);

  14. getch();
  15. return 0;
  16. }

No comments:

Post a Comment