Beginner · Operators and control flow · topic 7 of 60 · 20 min
Type conversion and casting
Explanation
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
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 arithmeticThe 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
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 ~foreverFloating point to integer
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
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!)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
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.
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.25Practice (0/3 done)
What does this print? int x = -5; unsigned int y = 3; printf("%s\n", x < y ? "yes" : "no");
int a = 9, b = 4; Which gives 2.25?
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
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Decisions: if, else and switchOperators and control flow · same module
- Loops: for, while and do-whileOperators and control flow · same module
- Type conversion and reading inputJava Programming (Core to Spring Boot) · Getting started with Java
- Variables, types and constantsC++ Programming (modern C++ and DSA) · First steps: compiling, output, variables and input
- Operators, conversions and parsing inputC# and .NET · Getting started with C# and .NET
- Scalar types: numbers, bool and charRust Programming · Types, control flow and functions
Questions people ask about this
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).
What is static_cast<int>(9.99)?Related
Answer: 9
Converting a double to an int cuts off the fraction; it does not round.
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.
int x; printf("%d", x); inside main prints…Related
Answer: An unpredictable value (undefined behaviour)
Local variables are not initialised.
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
- 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.
- Module 2 exam: Operators and control flow · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
- Then the next module, Functions and arrays. 60 topics left in the course before the final exam.