Type casting in C is the process by which one type of data is forcibly converted into another type though is same cases, the conversion from one type to another takes place automatically, there may be cases where the programmer forces the conversion of a data type to another. The later case is called explicit type casting. As for example let 'i' and 'j' be two integer variables and 'k' a float variable.
Thus
i=15; j=14; k=i/j; results is k = 3.0 (though 15/4 =3.75 ) as happens in integer-integer division. To assign 3.75 to 'k' would require type casting of one of 'i' and 'j' to float like k = (float)i/j; or k=i/(float)j;.
Type casting are useful in suitably casing a 'void' pointer to the proper type before use. (A 'void' pointer is a pointer that has no particular data type attached to it, and thus no pointer arithmetic applicable to it, though it can point to any data types.) The standard memory allocating function malloc() returns a void pointer pointing to the first block, which therefore needs to be suitably type casted before use, like
int *ptr;
ptr=(int*)malloc(10*sizeof(int));
Thus
i=15; j=14; k=i/j; results is k = 3.0 (though 15/4 =3.75 ) as happens in integer-integer division. To assign 3.75 to 'k' would require type casting of one of 'i' and 'j' to float like k = (float)i/j; or k=i/(float)j;.
Type casting are useful in suitably casing a 'void' pointer to the proper type before use. (A 'void' pointer is a pointer that has no particular data type attached to it, and thus no pointer arithmetic applicable to it, though it can point to any data types.) The standard memory allocating function malloc() returns a void pointer pointing to the first block, which therefore needs to be suitably type casted before use, like
int *ptr;
ptr=(int*)malloc(10*sizeof(int));
No comments:
Post a Comment