Argument Coercion in C/C++?

Argument coercion in C is a technique where the compiler automatically converts function arguments from one data type to another during function calls. This follows the argument promotion rule − lower data types can be implicitly converted to higher data types, but not vice versa. The reason is that converting higher data types to lower ones may result in data loss.

Syntax

return_type function_name(parameter_type param);
// Arguments are automatically coerced to match parameter types

Type Promotion Hierarchy

The following SVG shows the implicit conversion hierarchy in C −

Argument Coercion Hierarchy long double double float long int char Automatic Promotion Higher Precision

Example: Function with Double Parameters

This example demonstrates how integer arguments are automatically promoted to double when passed to a function expecting double parameters −

#include <stdio.h>

double myAdd(double a, double b) {
    return a + b;
}

int main() {
    printf("Double data add: %.1f\n", myAdd(5.3, 6.9));
    printf("Integer data add (promoted): %.1f\n", myAdd(6, 5));
    return 0;
}
Double data add: 12.2
Integer data add (promoted): 11.0

Example: Mixed Data Type Operations

This example shows argument coercion with different data types −

#include <stdio.h>

float calculate(float x, float y) {
    printf("Inside function: x=%.2f, y=%.2f\n", x, y);
    return x * y;
}

int main() {
    int a = 5;
    char b = 3;
    float result;
    
    printf("Original values: a=%d, b=%d\n", a, b);
    result = calculate(a, b);  // int and char promoted to float
    printf("Result: %.2f\n", result);
    return 0;
}
Original values: a=5, b=3
Inside function: x=5.00, y=3.00
Result: 15.00

Key Points

  • Argument coercion happens automatically during function calls when data types don't match exactly.
  • Promotion always goes from lower precision to higher precision to prevent data loss.
  • Common promotions: char ? int, int ? float, float ? double.
  • No automatic demotion occurs (e.g., double to int) without explicit casting.

Conclusion

Argument coercion in C provides automatic type conversion during function calls, following a strict hierarchy from lower to higher precision data types. This feature helps prevent data loss while maintaining code flexibility and type safety.

Updated on: 2026-03-15T11:00:41+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements