views:

90

answers:

2

Hi,

I have difficulty understanding the article Cast the return value of a function that returns a floating point type

(1) In

Conversion as if by assignment to the type of the function is required if the return expression has a different type than the function, but not if the return expression has a wider value only because of wide evaluation.

What is "wide evaluation"? What does it try to say?

(2) in the example

float f(float x) {  
  return x * 0.1f;  
}  

float g(float x) {  
  return x * 0.1;  
}  

Why "Function f is allowed to return a value wider than float, but function g (which uses the wider constant) is not"?

In f(), x and 0.1f are both float type so I think x * 0.1f is also float type? In g(), 0.1 is probably regarded as double, so x * 0.1 is double?

(3) What's the moralities of the article?

Thanks and regards!

+2  A: 

Function g returns type float which is a 32 bit value. 0.1 is interpreted as a double which means that the expression x * 0.1 returns a double. A double is a 64 bit value which will cause a narrowing conversion in order to be returned as a float. x can safely be converted to a double because that is a widening conversion from float to double.

Vincent Ramdhanie
+1  A: 

(1) In

Conversion as if by assignment to the type of the function is required

if the return expression has a different type than the function, but not if the return expression has a wider value only because of wide evaluation.

What is "wide evaluation"? What does it try to say?

If you declare a byte variable or constant, it may actually be stored as DWORD on 32-bit platform. Byte arithmetics may also be implemented as 32-bit arithmetics (wide evaluation). It does not cause problems for integer types.

(2) in the example

float f(float x) { return x * 0.1f; }

float g(float x) { return x * 0.1; }

Why "Function f is allowed to return a value wider than float, but function g (which uses the wider constant) is not"?

That is what the current C standard says: 0.1f may be stored in a wider format (than float), x * 0.1f may also be evaluated in a wider format, and return operator is not required to perform conversion to float and may return the result "as is". With the g function, the return operator is required to perform a conversion from double to float.

In f(), x and 0.1f are both float type so I think x * 0.1f is also float type? In g(), 0.1 is probably regarded as double, so x * 0.1 is double?

Yes, that is right for all 32-bit compilers (at least I think so :) ). But the article is dealing with the issue in general.

(3) What's the moralities of the article?

The C standard is a hard thing to learn :)

Serg