Typecasting in C converts a variable from one data type to another. C handles implicit type promotion automatically during mixed-type expressions, but explicit typecasting using (target_type) is required to prevent integer division truncation and pointer type mismatch warnings.
Implicit vs Explicit Typecasting Code Example
#include <stdio.h>
int main(void) {
int total = 17;
int count = 5;
// Integer Division without casting (Truncates fractional part -> 3.00)
double result_truncated = total / count;
// Explicit Typecasting (Promotes total to double -> 3.40)
double result_precise = (double)total / count;
printf("Without Cast: %.2f\n", result_truncated);
printf("With Cast: %.2f\n", result_precise);
// Pointer casting (void* to int*)
void *generic_ptr = &total;
int *int_ptr = (int *)generic_ptr;
printf("Dereferenced Cast Pointer: %d\n", *int_ptr);
return 0;
}
Comments and corrections