• Home
  • 4.1 Implicit Type Conversion

4.1 Implicit Type Conversion

View Categories

4.1 Implicit Type Conversion

Implicit type conversion occurs when C automatically converts a value from one type to another. It commonly happens during assignments, arithmetic operations, and function calls.

#include <stdio.h>

int main(void)
{
    int number = 10;
    double result = number;

    printf("Integer: %d\n", number);
    printf("Double: %.2f\n", result);

    return 0;
}

Example Output #

Integer: 10
Double: 10.00

Explanation #

The assignment:

double result = number;

converts the value of number from int to double automatically. The value 10 becomes 10.0.

Implicit conversion can also occur in arithmetic expressions:

int count = 5;
double average = count / 2.0;

Because 2.0 is a double, count is converted to double before the division. The result is 2.5.

Common Implicit Conversions #

Situation Example Conversion
Assignment double x = 5; int to double
Arithmetic 5 + 2.0 int to double
Function argument printf("%f", 1); The integer argument is not automatically suitable for %f; this format use is incorrect
Character arithmetic 'A' + 1 Character constant participates as an int expression in C

Implicit conversion does not always preserve the original value. For example:

int number = 3.9;

converts 3.9 to 3 because conversion from floating point to integer discards the fractional part when the value is representable.

The precise conversion rules depend on the types involved and the context in which the conversion occurs.

Powered by BetterDocs

Leave a Reply

Your email address will not be published. Required fields are marked *