Skip to content

Module 2 · Variables, Types, Input and Operators — topic 6 of 6

Type Conversion

C converts between types automatically in mixed expressions (implicit conversion) and lets you convert deliberately with casts. Learn the usual arithmetic conversions, integer promotion and the traps of narrowing and signed/unsigned mixing.

Beginner 14 min read·Lesson 10 of 37 in C Programming

Learning objectives

  • Apply integer promotion and the usual arithmetic conversions
  • Use casts to control division and rounding
  • Recognise data loss from narrowing and signed/unsigned comparisons

Definition

Type conversion changes a value from one type to another. Implicit conversions are applied by the compiler according to the usual arithmetic conversions and assignment rules; explicit conversions are written with a cast operator (type)expression.

Introduction

When you write 5 / 2.0, C cannot divide an int by a double directly. It first converts the 5 to 5.0, then divides. These automatic conversions happen constantly and usually do what you want.

Sometimes they do not: assigning 3.99 to an int silently gives 3, and comparing -1 with an unsigned value can say −1 is larger. Understanding the rules lets you predict and control the result.

Why it matters

Conversion bugs compile without errors, so they survive until a strange result appears in production. Knowing where conversions happen is how you find them.

Casting is also a deliberate tool — for exact averages, for indexing with characters, and for working with malloc's void * in C++-compatible code.

Detailed explanation

Integer promotion: in expressions, char, short and _Bool values are first converted to int (or unsigned int if int can't hold every value). So char a = 100, b = 100; int c = a + b; gives 200 — the addition is done in int.

Usual arithmetic conversions: when two operands have different types, the “lower” one is converted to the “higher”: int → long → long long, and any integer → float → double → long double. If one operand is unsigned of the same rank, the signed one is converted to unsigned.

Assignment conversion: the right-hand value is converted to the left-hand type. Converting a floating value to an integer truncates toward zero ((int)-2.7 is −2). If the value does not fit, the result is undefined for floating → integer, and implementation-defined for a too-large integer stored in a signed type.

Explicit cast: (double)x converts x. A cast binds tightly: (double)a / b casts a first, then divides as double; (double)(a / b) divides as integers first.

Signed meets unsigned

In -1 < 1u, the -1 is converted to unsigned int — the huge value 4294967295 — so the comparison is false. Compilers warn with -Wextra (-Wsign-compare).

Syntax

C
double avg = (double)sum / count; /* explicit cast */
int whole = (int)3.99; /* 3: truncates */
long total = n * 1L; /* promotes n to long */
double r = 7 / 2.0; /* implicit: 7 -> 7.0 */
  • A cast is written (type) before an expression.
  • Casting to a narrower type may lose information.
  • Casts do not change the original variable; they produce a converted value.

Code examples

Implicit and explicit conversion

C
#include <stdio.h>
int main(void) {
int a = 7, b = 2;
printf("%d\n", a / b);
printf("%.1f\n", a / 2.0);
printf("%.1f\n", (double)a / b);
printf("%.1f\n", (double)(a / b));
return 0;
}
Output
3
3.5
3.5
3.0

Truncation, not rounding

C
#include <stdio.h>
int main(void) {
double x = 9.99, y = -9.99;
int i = x, j = y;
printf("%d %d\n", i, j);
printf("%d\n", (int)(x + 0.5));
return 0;
}
Output
9 -9
10

Adding 0.5 before truncating rounds positive numbers; round() from <math.h> handles both signs.

More examples

Promotion, characters and the unsigned trap

C
#include <stdio.h>
int main(void) {
char c1 = 100, c2 = 100;
int sum = c1 + c2; /* computed as int */
printf("char sum as int: %d\n", sum);
char letter = 'a';
printf("%c -> %c\n", letter, letter - 32);
printf("'7' as digit: %d\n", '7' - '0');
int neg = -1;
unsigned int pos = 1;
if (neg < (int)pos)
printf("with a cast: -1 < 1\n");
if (!((unsigned)neg < pos))
printf("as unsigned, -1 becomes %u\n", (unsigned)neg);
return 0;
}
Output
char sum as int: 200
a -> A
'7' as digit: 7
with a cast: -1 < 1
as unsigned, -1 becomes 4294967295

Step-by-step explanation

  • c1 + c2 promotes both chars to int, so 200 is computed without overflowing a char.
  • letter - 32 works because characters are small integers: 'a' is 97 and 'A' is 65 in ASCII.
  • '7' - '0' converts a digit character to its numeric value — a common parsing idiom.
  • Casting pos to int keeps the comparison signed, so −1 < 1 as expected.
  • Converting −1 to unsigned gives the maximum value, which is why mixing them silently breaks comparisons.

Expected output

Running “Promotion, characters and the unsigned trap” prints exactly:

TextOutput
char sum as int: 200
a -> A
'7' as digit: 7
with a cast: -1 < 1
as unsigned, -1 becomes 4294967295

Practical applications

  • Parsers convert digit characters with c - '0'.
  • Graphics code casts between float coordinates and int pixel positions.
  • Security bugs often come from a negative length converted to a huge unsigned size.

Best practices

  • Cast one operand, not the whole expression, when you need real division.
  • Keep signed and unsigned values apart; enable -Wextra to catch mixed comparisons.
  • Use round, floor and ceil from <math.h> when you mean rounding.

Common mistakes

Casting after the division

Avoid

double avg = (double)(total / n);

Prefer

double avg = (double)total / n;

Parentheses force integer division first, so the fraction is already lost when the cast happens.

Comparing a signed index with sizeof

Avoid

int i = -1;
if (i < sizeof(int)) { /* false! */ }

Prefer

int i = -1;
if (i < (int)sizeof(int)) { /* true */ }

sizeof yields an unsigned size_t; i is converted to a huge unsigned value.

Important notes

  • Converting a floating value that is out of the target integer's range (e.g. (int)1e20) is undefined behaviour.
  • 'a' - 32 relies on ASCII; portable code uses toupper from <ctype.h>.

Key takeaways

  • Small integer types are promoted to int in expressions.
  • Mixed operands convert toward the wider or floating type; signed may become unsigned.
  • Casting a floating value to an integer truncates toward zero.

Try it yourself

  1. 1
    Read a temperature in Fahrenheit as an integer and print Celsius with one decimal using (f - 32) * 5 / 9.0. Then try 5 / 9 and explain the difference.
  2. 2
    Write toupper-like logic: convert a lower-case letter to upper case using arithmetic, only if it is between 'a' and 'z'.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

8 questions test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
  • BeginnerWhat is printed?
  • BeginnerWhat is printed?
Practise this topic