C
Beginner
1 min read
Type Conversions and Casting
Example
#include <stdio.h>
int main(void)
{
int a = 7;
int b = 2;
double result;
/* Integer division — truncates toward zero */
printf("7 / 2 (int) = %d\n", a / b); /* 3 */
/* Implicit promotion: int -> double */
result = a / (double)b;
printf("7 / 2.0 = %.1f\n", result); /* 3.5 */
/* Explicit cast to avoid truncation */
result = (double)a / b;
printf("(double)7 / 2 = %.1f\n", result); /* 3.5 */
/* Dangerous signed/unsigned comparison */
int neg = -1;
unsigned int pos = 1;
if ((unsigned int)neg > pos) {
/* This branch IS taken — -1 becomes a huge unsigned value */
printf("Signed/unsigned trap: -1 > 1 as unsigned\n");
}
/* Safe truncation via explicit cast */
double pi = 3.14159;
int trunc = (int)pi;
printf("(int)3.14159 = %d\n", trunc); /* 3 */
return 0;
}