Skip to main content

Type Conversion in C

2 min read Updated May 29, 2025
Share:
On this page (11sections)

Introduction

Type conversion (also called type casting) changes a value from one data type to another. C performs some conversions automatically; others require an explicit cast.

Implicit Conversion

When operands of different types appear in an expression, C promotes the smaller type to the larger:

int a = 5;
float b = 2.5f;
float result = a + b;   /* int 5 promoted to float 5.0 */

In assignment, the right-hand value is converted to the left-hand type:

float f = 9;       /* int 9 → float 9.0 */
int n = 3.14f;     /* float truncated → int 3 */

Explicit Conversion (Casting)

Use (type) before a value to force conversion:

#include <stdio.h>

int main(void) {
    float pi = 3.14159f;
    int whole = (int)pi;

    printf("pi as float: %.5f\n", pi);
    printf("pi as int:   %d\n", whole);
    return 0;
}

Sample Output

pi as float: 3.14159
pi as int:   3

Integer Division vs Float Division

A common conversion pitfall:

#include <stdio.h>

int main(void) {
    int a = 5, b = 2;
    printf("int division:   %d\n", a / b);           /* 2 */
    printf("float division: %.1f\n", (float)a / b);   /* 2.5 */
    return 0;
}

Sample Output

int division:   2
float division: 2.5

Cast before division to avoid truncating the result.

char and int Conversion

char is a small integer type. Characters and their ASCII codes convert freely:

char ch = 'A';
printf("char: %c, code: %d\n", ch, ch);   /* A, 65 */

Best Practices

  • Cast explicitly when the conversion affects correctness (especially division).
  • Be aware of truncation when casting floating-point to integer.
  • Use (float) or 3.14f to ensure floating-point arithmetic.

Common Mistakes

  • (int)(3.9) gives 3, not 4 — no rounding.
  • Overflow when converting a large long to int on systems where sizes differ.
  • Forgetting that a / b with two integers always produces an integer result.

Continue learning with these related tutorials and programs:

Frequently Asked Questions

What is the difference between implicit and explicit conversion?
Implicit conversion happens automatically (e.g. int to float in mixed arithmetic). Explicit conversion uses a cast: (type)value.
What happens when you cast float to int?
The fractional part is truncated (not rounded). (int)3.9 becomes 3, not 4.

Related Tutorials

Search tutorials