Site icon TestingDocs.com

C Typecasting

Overview

In this tutorial, we will learn about Typecasting in the C language. It is a good programming practice to use the cast operator whenever type conversions are necessary for the code.

What is Typecasting?

Typecasting is a way to convert a variable from one data type to another data type. This process is also known as type conversion. For example, we can convert an integer to a double value.

Typecasting can be two types:

 

Implicit Typecasting

Type conversions can be implicit and are performed by the compiler automatically without the intervention of the programmer.

int ch=97;
printf(“Character : = %c \n”, ch); //Implicit Typecasting

The compiler automatically converts the integer data type to a character data type.

Explicit Typecasting

Explicit typecasting is done by the programmer explicitly through the use of the cast operator.

Syntax

We can convert values from one data type to another explicitly using the cast operator. C allows programmers to perform typecasting by placing the target type name in parentheses ( )
and placing this in front of the value/expression. The general syntax of the explicit type casting is as follows:

(datatype_name) value / expression

For example, to convert the integer 7 to a floating point value:

float result;
result = (float)7 ;

Example

Consider the following example where the cast operator causes the division of one integer variable by another to be performed as a floating-point operation:

/**
**********************************
* Program Description:
* C Typecasting Demo
* Filename : typecast.c
* C Tutorials - www.TestingDocs.com
*************************************
*/
#include<stdio.h>

int main()
{
    /* Local variables declaration */
    int a = 20, b = 3;
    double result;

    result = (double) a / b;

    printf("Result of a/b: %lf \n", result);
    return 0;

} // end main


Save the C program. Compile and Run the code. It produces the following result:

Result of a/b: 6.666667

The type cast operator has precedence over the division operator, so the value of a is first converted to type double and is divided by b yielding a double value. We need to type cast because the value of the expression would be incorrect.

result = a / b;

Remove the type cast in the program and examine the program output. The value of the result would be incorrect.

We should take care when we use typecasting. Incorrect usage may result in the loss of data.
For example, the floating point value may be truncated when cast to the type int.

C Tutorials

C Tutorials on this website can be found at:

https://www.testingdocs.com/c-language-tutorial/

Exit mobile version