16 Type Casting
16 Type Casting
Operation Result
5/2 2
5.0 / 2 2.500000
5 / 2.0 2.500000
int i = 2/9; 0
float f = 2/9; 0.000000
int i = 2.0/9; 0
int i = 2.0/9.0; 0
int i = 9/2; 4
int i = 9.0/2; 4
int i = 9/2.0; 4
int i = 9.0/2.0; 4
Here are some common scenarios where implicit type casting occurs in C:
Assignment: When you assign a value of one data type to a variable of another data type,
C may perform implicit type casting to make the assignment compatible.
For example:
int integerVar = 42;
double doubleVar = integerVar; // Implicit casting from int to double
int num1 = 5;
double num2 = 2.5;
double result = num1 + num2; // Implicit casting of int to double
Comparison Operators: When comparing values of different data types, C will perform
implicit casting to make the comparison valid.
For example:
int intValue = 5;
double doubleValue = 5.0;
if (intValue == doubleValue) {
// Implicit casting of int to double for comparison
}
Function Arguments: When you pass arguments to a function, and the function expects a
different data type than what you're passing, C may perform implicit type casting.
For example:
Note: It's important to note that implicit type casting can lead to unexpected behavior
and data loss if you're not careful. Therefore, it's essential to be aware of the C language's
rules for implicit type casting and make explicit type conversions (using casting operators
like (type)) when necessary to ensure the desired behavior and avoid potential issues.
In C, explicit type casting is the process of converting a value from one data type to
another by using casting operators. Explicit type casting allows you to control and
specify the conversion you want, and it's especially useful when you need to convert
between incompatible data types. The casting operator in C is denoted by enclosing
the target data type in parentheses before the value or expression you want to
convert.
Example:
#include <stdio.h>
int main() {
float a;
int x = 6, y = 4;
a = (float)x / y; // Explicitly cast x to float for division
printf("Value of a = %f\n", a);
return 0;
}
(dataType)value
The dataType can be any C data type, such as int or float. The value is any variable,
literal, or expression. Suppose that age is an integer variable that holds 6. The
following converts age to a float value of 6.0:
(float)age;
Note: variable—age is changed only temporarily for this one calculation. Everywhere in
the program that age is not explicitly typecast, it is still an int variable.
Operation Result
Note: Explicit type casting should be used with caution because it allows you to perform
potentially unsafe conversions. When using explicit casting, be aware of the potential for
data loss, precision issues, or undefined behavior if the conversion is not meaningful or
compatible.