Skip to content

Beginner · Operators and control flow · topic 7 of 60 · 20 min

Type conversion and casting

Explanation

C converts types automatically in expressions: small integers (char, short) become int ("integer promotion"), and mixed operands are converted to a common type, such as int to double. Mixing signed and unsigned can surprise you: -1 < 1U is false. A cast like (double) total / count forces a conversion; converting a double to int truncates.

Why conversions happen

An expression like 5 + 2.5 mixes an int and a double. The processor cannot add them directly, so C converts one operand so both have the same type before calculating. These automatic conversions follow fixed rules that are mostly helpful, but a few produce famous bugs.

Integer promotion

c
char a = 100, b = 100;
int sum = a + b;          // 200: a and b are promoted to int before adding
printf("%d\n", sum);
unsigned char c = 200;
printf("%d\n", c + 100);  // 300: still int arithmetic

The usual arithmetic conversions

If one operand is double, the other becomes double. Otherwise, if one is long long, the other becomes long long, and so on up to int. So int + double gives double, and int * long gives long.

The signed / unsigned trap

c
int balance = -1;
unsigned int limit = 1;
if (balance < limit) printf("less\n");
else printf("NOT less!\n");          // prints NOT less!: -1 is converted to 4294967295

size_t len = strlen("abc");          // size_t is unsigned
for (int i = 0; i < len - 4; i++) { } // len - 4 wraps to a huge number: the loop runs ~forever
Careful: When a signed and an unsigned int meet, the signed value is converted to unsigned, so negative numbers become huge positive ones. Avoid mixing them: keep sizes and indexes as size_t and compare carefully, and compile with -Wextra (which enables -Wsign-compare) to get warnings.

Floating point to integer

c
double price = 99.99;
int rupees = price;               // 99: truncation, not rounding
int rounded = (int)(price + 0.5); // 100 for positive numbers
#include <math.h>
long r = lround(price);           // 100: proper rounding (link with -lm on Linux)

Converting a floating value that is out of range for the integer type (for example 1e20 to int) is undefined behaviour.

Casts

c
int total = 7, count = 2;
double avg1 = total / count;            // 3.0 (integer division, then converted)
double avg2 = (double) total / count;   // 3.5 (cast first, then double division)
double avg3 = (double) (total / count); // 3.0 (cast applied too late!)
A cast binds tighter than /, so (double) total / count casts only total.
Think of it like this: Mixing types is like adding rupees and paise on a bill: before adding, everything is converted to one unit. Usually that is fine, but if a negative amount is written in a column that only accepts positive numbers (unsigned), it turns into a huge wrong figure.
Tip: Write casts only when you mean them, and put them where the conversion must happen: (double) a / b, not (double)(a / b).

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Type conversion and casting · 1/6

Type conversion

In this lesson you will see how C converts between types.

Prefer a video by a teacher? Find free videos on “c implicit type conversion integer promotion signed unsigned casting” on YouTube ↗

In real life: Average marks on a results portal

A school results program showed every class average as a whole number because it divided the integer total by the integer count. Casting the total to double before dividing fixed the report.

c
int marks[] = {78, 85, 91, 67};
int total = 0, n = 4;
for (int i = 0; i < n; i++) total += marks[i];   /* total = 321 */
printf("Wrong: %.2f\n", (double)(total / n));   // 80.00
printf("Right: %.2f\n", (double) total / n);    // 80.25

Practice (0/3 done)

Task 1 · Question

What does this print? int x = -5; unsigned int y = 3; printf("%s\n", x < y ? "yes" : "no");

Task 2 · Question

int a = 9, b = 4; Which gives 2.25?

Task 3 · Practice

Write a program that reads total marks and number of subjects as ints and prints the average three ways: integer division, a cast in the wrong place, and the correct cast. Then print lround(average). Explain each output in a comment.

Quick quiz

Question 1

1.What is (int) 7.9?

Question 2

2.What type is the result of 3 + 2.0?

Question 3

3.Why can comparing an int with a size_t be dangerous?

Question 4

4.In char a = 100, b = 100; int c = a + b; what is c?

Read more (free)

Before this, learn

This topic builds on these. If something here feels new, open them first.

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

What is (int) 7.9?

Answer: 7

Conversion to int truncates.

What type is the result of 3 + 2.0?

Answer: double

The int is converted to double.

Why can comparing an int with a size_t be dangerous?

Answer: A negative int is converted to a huge unsigned value

Signed/unsigned comparison.

In char a = 100, b = 100; int c = a + b; what is c?

Answer: 200

Promotion to int prevents overflow in the addition.

Which conversion needs an explicit cast?Related

Answer: double to int

double to int may lose information (narrowing).

From Type conversion and reading input

What is static_cast<int>(9.99)?Related

Answer: 9

Converting a double to an int cuts off the fraction; it does not round.

From Variables, types and constants

int a = 10, b = 4; double r = a / b; What is r?Related

Answer: 2

a / b is integer division (2) before the result is stored in the double, so r is 2.

From Operators, conversions and parsing input

int x; printf("%d", x); inside main prints…Related

Answer: An unpredictable value (undefined behaviour)

Local variables are not initialised.

From Data types and their sizes

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 3 more topics in “Operators and control flow” before its exam: Decisions: if, else and switch, Loops: for, while and do-while, Solving problems with loops.
  2. Module 2 exam: Operators and control flow · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, Functions and arrays. 60 topics left in the course before the final exam.

← Previous: Operators