C Type Casting

In this tutorial you will learn about the C Type Casting and its application with practical example.

Here you know about type casting is a mechanism in the c programming language that enables a variable of one data type to be converted to another datatype. When a variable is typecasted into a different type, the compiler basically treats the variable as the new data type.

Type of casting

  • implicit or automatic
  • explicit or given

implicit or automatic

An 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 afloat.

Example:

Here the 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 the right order (low to the higher data type). Typecasting in wrong places may result in loss of precision, which the compiler can signal with a warning. for example, instance truncating afloat 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 of conversion explicit, or to force it when it wouldn’t normally happen. To perform typecasting, 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 –

 

In this tutorial we have learn about the C Type Casting and its application with practical example. I hope you will like this tutorial.