代码中有多少类型转换?

时间:2016-07-11 18:40:00

标签: c type-conversion type-promotion

以下代码中有多少种类型转换:

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

在功能f()中,返回值从int提升为float。 在main()中,f()的参数从int提升为longint再次提升为float

有三种类型转换(促销)是否正确?

3 个答案:

答案 0 :(得分:4)

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().)

答案 1 :(得分:2)

In f:

int (argument) -> float (cast) -> int (return value)

In main:

long (literal) -> int (argument)

int (return value of f) -> float ( variable x)

That's four conversions.

答案 2 :(得分:0)

There is no single correct answer to this question - it all depends on the compiler and the system used.

A good compiler will through everything except the return 0; away and there will be no conversions at all.

Even if the compiler still keeps the function, the number of conversions is still unpredictable. The 5L to int conversion will be resolved at compile time. So it shouldn't count as a conversion. Also on many system there is no difference between long and int as they are both 32 bits (on many systems) which again suggest this isn't a conversion.

On most systems, the ugly (float) cast causing int->float->int will have to stay as a float can't represent all values of an int. But if the system uses a float format that can represent all int values, the compiler may through the conversions away. The int->float in main would have to stay.

So I would say either 0, 1 or 3 conversions. With 0 being mostly likely when compiling with optimization.

But the real answer is - it is system and compiler dependant.