Monday, July 8, 2013

Type Casting in C

Type Casting is nothing converting one data type value into another data type value. In C, we do have type casting where in we can convert a data type into another data type. Based on the type of conversion, we have two types of conversion.

  1. Implicit
  2. Explicit
Both these conversions are for converting one data type value into another data type but the difference lies with, whether we mention to convert or it automatically converts. Lets get more briefly into the topic.

Implicit Conversion:

Implicit conversion is that which we need not to mention. C itself converts from one data type to another data type without we specifying to convert.

For example, if we want to place an integer value into a float value, it doesn't need any explicit saying. We can directly use that conversion.
  • int a=3;
  • float b=a;
Then it takes the value of b as 3.000000 which is double precision value.

Explicit Conversion:

Explicit conversion is that which we have to specify to convert. Generally a data type which takes less number of bytes can be easily converted to a type which has more bytes i.e., an integer can be converted to float easily without mentioning to be converted.

In the topic of Data Structures, you will need to allocate the memory dynamically by using malloc function. In such a creation, it just gives the memory but doesn't take care of the type. In such cases we have to mention that this memory is used for storing some type of data.

For example,
node=(struct temp *)malloc(sizeof(int));
In such a creation we are creating a memory of size int and specifying that the memory we are going to store is of structure temp.