Programmer Coding

Type Casting in C Language

Type Casting in C?

Data types are important in determining the nature and behavior of changes in business. Format conversion allows us to convert one file format to another. This technique is called type casting, and the C programming language provides it as a useful tool. In this blog we will look at the syntax, implementation and advantages of type conversion in C.

The process of changing the format of different files is called format conversion. It is useful in many situations, such as when logging in, performing mathematical calculations, or interacting with other libraries that require data types. In C, we use the cast operator to perform type conversion, represented by (type).

Types of Type Casting

 

  1. Implicit Casting

  2. Explicit Casting

 

  • Implicit Casting

When the compiler automatically converts data from one type to another, it is called implicit conversion or automatic type conversion. This change is based on a set of instructions indicating how many documents can be integrated. For example, automatically converting an integer to a floating-point number without explicit instructions is an example of implicit conversion.

Example

#include <stdio.h>

int main() {

int num1 = 10;

float num2 = 5.5;

// Implicit type conversion: int is promoted to float

float result = num1 + num2;

printf(“Result: %f\n”, result);

return 0;

}

Output

Result: 15.500000

  • Explicit Casting

Using the cast operator, a clear expression is required to convert from one data type to another. It requires explicit instructions in the program code and allows the programmer to control the type of change.

Example

#include <stdio.h>

int main() {

float num1 = 10.5;

float num2 = 5.5;

// Explicit type casting: float is converted to int

int result = (int)num1 + (int)num2;

printf(“Result: %d\n”, result);

return 0;

}

Output

Result: 15

Narrowing Conversion

 

Converting the price to a data type with a narrow range or precision is called narrow transformation and this causes data loss. If not treated appropriately, this will lead to bad behavior that needs to be addressed.

Example

#include <stdio.h>

int main() {

double num1 = 1234.5678;

int num2;

// Explicit type casting: double is converted to int

num2 = (int)num1;

printf(“num1 (double): %f\n”, num1);

printf(“num2 (int): %d\n”, num2);

return 0;

}

Output

num1 (double): 1234.567800

num2 (int): 1234

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top