C Type Casting

Type Casting is a mechanism in c programming language which enables a variable of one datatype to be converted to another datatype.When a variable is typecasted into a different type, the compiler basically treats the variable as of the new data type.

Type of casting

  • implicit or automatic
  • explicit or given

implicit or automatic

In implicit or automatic casting compiler will automatically change one type of data into another. For instance, if you assign an integer value to a floating-point variable, the compiler will insert code to convert the int to a float.

Example:

Here value of 'a' has been promoted from short to int and we have not had to specify any type-casting operator. implicit conversions affect fundamental data types. Typecasting should always be used in right order (low to higher datatype).Typecasting in wrong places may result in loss of precision, which the compiler can signal with a warning. for example like for instance truncating a float when typecasting to an int.This can be avoided with an explicit conversion. Below is the right order for numerical conversion.

short int -> int -> unsigned int ->long int -> unsigned long int -> float -> double -> long double

explicit or given

Casting allows you to make this type conversion explicit, or to force it when it wouldn’t normally happen.To perform type casting, put the desired type including modifiers (like double) inside parentheses to the left of the variable or constant you want to cast.

Example:

type casting from char to int results in ASCII code –