CodeBlanks Logo Icon CodeBlanks

Type conversion

Learn implicit and explicit (cast) type conversion.

Type conversion

Type conversion means turning a value into another type. There are two kinds:

  • Implicit: the compiler does it automatically (e.g., int x = 3.7;)
  • Explicit: done with the cast operator ((int)3.7 → 3)

Explicit conversion, also called a cast, is safer because it states your intent clearly and silences warnings.

Conversion rules

Type conversion in C follows clear rules:

  • int to double: safe, no data loss
  • double to int: decimal part is lost
  • Conversion to a smaller type risks overflow

Type matching matters especially in division: 7 / 2 gives 3 (integer division), but 7.0 / 2 gives 3.5 (double division).

Practice Print with cast

Add to the program below a line that casts d to int with (int) d, and a printf call. The output should be 9 9.700000.

Starter code

main.c
#include <stdio.h>

int main(void) {
    double d = 9.7;
    // cast to int and print with printf
    return 0;
}

Sample solution

main.c
#include <stdio.h>

int main(void) {
    double d = 9.7;
    int i = (int) d;
    printf("%d %lf", i, d);
    return 0;
}

Expected output

9 9.700000

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does (int)3.7 return?

  • 4
  • 3 Correct answer
  • 3.7
  • 0

Explanation: (int)3.7 drops the decimal part and gives 3.

2 Cast operator

Question
int x = (____) 3.7;
Answer
int x = (int) 3.7;

Explanation: (int) converts a value to int.

3 Match conversion concepts

Term Meaning
(int) To int
(double) To double
implicit Automatic
explicit Cast

All lessons in Beginner