Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 135 ยท Variables and Types

Type Conversions and Casts

Understand C type conversions - integer promotion, the usual arithmetic conversions, signed/unsigned comparison traps, narrowing, float-to-int truncation and explicit casts.

C lets you mix types freely. You can add a char to a double, store a long in a short, or compare an int with a size_t, and the compiler will quietly convert values to make the operation work. Most of the time these implicit conversions do what you expect. Occasionally they produce results that look impossible, like -1 < 1u being false, or 5 / 2 * 2.0 being 4.0.

Every one of those surprises follows from a small set of rules. This lesson walks through them in the order the compiler applies them: integer promotion, the usual arithmetic conversions, conversions on assignment and function calls, and finally explicit casts, where you tell the compiler exactly which conversion you want.

When conversions happen

C converts values implicitly in these situations:

  1. In arithmetic and comparisons, when the operands have different types (int + double).
  2. On assignment and initialization, when the value's type differs from the variable's (int n = 3.9;).
  3. When calling a function, when an argument's type differs from the parameter's type in the prototype.
  4. When returning, when the returned expression's type differs from the function's return type.
  5. In conditions, where any scalar is compared with zero (see Booleans).

Converting to a type that can represent every value of the original (like int to long long, or float to double) is a widening conversion and is always safe. Converting to a type that can't (like double to int, or int to unsigned char) is a narrowing conversion, and that's where information gets lost.

Integer promotion

C never does arithmetic directly in types smaller than int. Before an operation, any char, short, bool or bit-field value (signed or unsigned) is promoted to int if int can hold all its values, otherwise to unsigned int. On every common platform that means "small types become int".

C Small types are promoted to int

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

a + b is 300, not 44, because both operands become int before the addition. The result is truncated only when it's stored back into an unsigned char. Even a lone unary + promotes, which is why sizeof(+c) is 4.

The last line is a classic promotion trap. ~x flips the bits of the promoted int 0x0000000F, giving 0xFFFFFFF0, which is โˆ’16 as an int. If you wanted the 8-bit result 0xF0 (240), cast back to unsigned char. Keep this in mind for Bitwise Operators.

The usual arithmetic conversions

When a binary operator like +, *, < or == gets two operands of different types, C converts them to a common type using the usual arithmetic conversions:

  1. If either operand is long double, the other becomes long double.
  2. Otherwise, if either is double, the other becomes double.
  3. Otherwise, if either is float, the other becomes float.
  4. Otherwise both are integers: first apply integer promotion to each, then:
    • If they have the same type, done.
    • If both are signed or both unsigned, the one with lower rank converts to the higher rank (int โ†’ long โ†’ long long).
    • If the unsigned operand has rank greater than or equal to the signed one, the signed operand becomes unsigned.
    • Otherwise, if the signed type can hold every value of the unsigned type, the unsigned operand becomes signed.
    • Otherwise both become the unsigned version of the signed type.

The floating-point steps hold no surprises: an integer meeting a double becomes a double. The trouble is almost always the "signed becomes unsigned" rule.

Because conversions apply per operator, the order of operations matters:

C Conversions happen one operator at a time

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

total / count * 1.0 is 3.0, not 3.5: the division happens first, between two ints, and throws away the fraction before 1.0 ever joins in. Converting an operand before the division, (double)total / count, gives 3.5. Casting the result, (double)(total / count), is too late. Likewise 5 / 2 * 2.0 is 4, not 5.

Signed and unsigned surprises

When an int meets an unsigned int, the rule above converts the int to unsigned int. A negative value becomes a huge positive number (โˆ’1 becomes 4,294,967,295), and comparisons go wrong. This example triggers compiler warnings on purpose; they're the point of the lesson:

C When -1 is greater than 1

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

GCC prints two -Wsign-compare warnings ("comparison of integer expressions of different signedness"), one for a < b and one for the strlen comparison, and the program shows why they matter. (The long long comparison gets no warning, because it's safe.)

  • a < b: a is converted to unsigned int, 4294967295, which is not less than 1.
  • wide < b: long long can represent every unsigned int value, so b is converted to long long instead, and the comparison works.
  • strlen(word) > min_length: strlen returns size_t, an unsigned type of rank long on our server, so โˆ’1 becomes 18446744073709551615.

The same rule makes strlen(s) - 5 > 0 true for a three-letter string: the unsigned subtraction wraps to a huge value instead of going negative. Write strlen(s) > 5 instead.

Read every -Wsign-compare warning. The fix is usually to make both sides the same signedness: use size_t for loop indexes compared with sizes, check that a signed value is non-negative before converting it (n >= 0 && (size_t)n < len), or rearrange subtractions on unsigned values into comparisons.

Conversions on assignment

When you store a value in a variable of a different type, it's converted to the variable's type. The rules depend on the direction:

From โ†’ To What happens
Any integer โ†’ wider integer of the same signedness Value preserved
Any integer โ†’ unsigned type that's too small Wraps modulo 2โฟ (well-defined): 300 โ†’ 44 for unsigned char
Any integer โ†’ signed type that's too small Implementation-defined (GCC keeps the low bits): 40000 โ†’ โˆ’25536 for short
Floating โ†’ integer Fraction truncated toward zero; undefined if the result doesn't fit
Integer โ†’ floating Exact if representable, otherwise rounded (large long long โ†’ double)
double โ†’ float Rounded to the nearest float; undefined if out of range
Any scalar โ†’ bool 0 stays 0, everything else becomes 1
C Narrowing conversions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Every narrowing above uses an explicit cast, which documents that the loss is intended. Without the casts, GCC stays silent for most of them under -Wall -Wextra. The extra flag -Wconversion warns about every implicit conversion that may change a value; it's noisy in old code but excellent for new code. The Floating-Point Numbers lesson shows how to round instead of truncating.

Out-of-range float-to-int conversions are undefined. (int)1e10 or (int)NAN may give INT_MIN, a random value or something else, depending on the CPU and the optimizer. Check the range first, for example if (x >= INT_MIN && x < INT_MAX + 1.0).

Conversions in function calls

When a function has a prototype (a declaration listing its parameter types), each argument is converted to the parameter's type as if by assignment. Passing 3 to a double parameter gives 3.0, and passing 2.7 to an int parameter gives 2.

Variadic functions like printf are different: the extra arguments have no declared type, so they only get the default argument promotions: char, short and bool become int, and float becomes double. Nothing converts an int to a double for you, which is why the format specifier must match:

C
printf("%f\n", 5);        // undefined behavior: an int where a double is expected
printf("%f\n", 5.0);      // correct
printf("%f\n", (double)5); // correct
printf("%d\n", 'A');      // fine: the char literal is already an int

GCC's -Wformat warning (part of -Wall) catches most mismatches. The Variadic Functions lesson explains the promotions from the callee's side.

Explicit casts

A cast converts a value to a type you name: (type)expression. The cast operator binds tighter than all binary operators, so (double)a / b converts a and then divides.

Good reasons to cast:

  • Force floating-point division: (double)sum / count.
  • Widen before an operation that might overflow: (long long)width * height.
  • Document an intended narrowing: (uint8_t)(value & 0xFF).
  • Pass the right type to a variadic function: printf("%lu", (unsigned long)n).
  • Prepare a char for <ctype.h>: toupper((unsigned char)c) (see Characters).
C Casting to get the result you mean

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Notice what's not cast: malloc returns void *, which converts implicitly to any object pointer type in C. Casting it, as in (double *)malloc(...), is required in C++ but unnecessary in C, and it can hide a missing #include <stdlib.h> in old compilers. The Dynamic Memory lesson covers this idiom.

Bad reasons to cast:

  • To silence a warning you don't understand. A cast tells the compiler "I know what I'm doing"; make sure you do.
  • To remove const. Writing through a pointer whose const was cast away is undefined behavior if the object really is const.
  • To reinterpret memory between unrelated pointer types, like *(float *)&some_int. That breaks the strict aliasing rules; use memcpy or a union instead, as shown in Unions.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. unsigned char a = 250, b = 10; What does printf("%d", a + b); print?

    Both operands are promoted to int before the addition, so the result is the int 260. It would only wrap to 4 if stored back in an unsigned char.
  2. 2. With a 32-bit int, what is -1 < 1u?

    The usual arithmetic conversions turn the signed -1 into unsigned int, 4294967295, which is not less than 1. GCC warns with -Wsign-compare.
  3. 3. What is the value of 7 / 2 * 2.0?

    Operators are evaluated left to right. 7 / 2 is integer division, giving 3, and only then is 3 multiplied by 2.0, giving 6.0.
  4. 4. Which expression computes the true average of the ints sum and count?

    Casting one operand before the division makes the division happen in double. The other options all perform integer division first, losing the fraction.
  5. 5. int n = (int)-3.8; What is n?

    Converting a floating value to an integer truncates toward zero, so -3.8 becomes -3. Use floor or lround from math.h for other rounding.

Summary

  • C converts values implicitly in expressions, assignments, function calls and returns; widening is safe, narrowing can lose information.
  • Integer promotion turns char, short and bool into int before any arithmetic.
  • The usual arithmetic conversions pick a common type: floating types win, then higher rank, and an unsigned operand of equal or higher rank turns the signed one unsigned.
  • Mixing signed and unsigned values makes -1 < 1u false; heed -Wsign-compare warnings.
  • Floating-to-integer conversion truncates toward zero and is undefined when the value doesn't fit.
  • Variadic functions only get default promotions, so printf specifiers must match the argument types.
  • Cast to force floating division, to widen before overflow, and to document intent; never cast just to silence a warning.

Next: Type Limits: limits.h and float.h, where you'll find the exact range of every type and learn to detect overflow before it happens.