Search code examples
ctype-conversiontype-promotion

How many type conversion are there in the code?


How many type conversion are there in the following code:

#include<stdio.h>
int f(int x)
{
    return (float)x;
}
int main()
{
    float x = f(5L);
    return 0;
}

In function f(), the return value is promoted from int to float. In main(), the argument of f() is promoted from int to long, and int is again promoted to float.

Is it correct that there are three type conversions (promotions)?


Solution

  • I see a total of 4 type conversions (none of which are "promotions").

    Inside f(), the value of x is explicitly converted from int to float by the cast operator, The result of that conversion is implicitly converted from float to int by the return statement.

    Inside main(), the value of the constant 5L is implicitly converted from long int to int when it's passed as an argument to f. The result of the call to f is implicitly converted from int to float by the initialization of x.

    That's four conversions. (The return 0; doesn't involve a conversion, since the 0 is already of type int, which is the return type for main.)

    Given a reasonably clever compiler, it's likely that none of these conversions will result in any non-trivial generated code. Since none of the values are used, the entire program could be reduced to the equivalent of

    int main(void) { return 0; }
    

    But all four conversions occur in the "abstract machine" defined by C's semantics.

    (Incidentally, int main(void) is preferred to int main().)