1

Which conversions take place when evaluating the following expressions?

char cval;
int ival;
float fval; 
// Assume all 3 have been set to correct values...
a) if(fval)
b) double dval = fval + ival; 
c) dval + ival + cval;

My thoughts:

a) I assume if needs a bool value, so the float gets implicitly casted to bool.

b) I assume that fval is promoted to double and ival is converted to a double, and then they are added.

c) First, ival is converted to a double. Then dval + ival gets evalutated, which is of type double. Then cval...I don't know if it gets converted to double directly, or if it it is promoted to int first. Anyway, after that step the temp value dval + ival is added to that double.

Is my understanding correct?

Maxpm
  • 24,113
  • 33
  • 111
  • 170
Chris
  • 2,030
  • 1
  • 16
  • 22
  • 3
    All three have undefined behaviour, because they involve reading from uninitialised values. – Mankarse Mar 23 '12 at 13:07
  • I can't find anything wrong, but I can't recite the standard on those points. However, I would say that you know the details better than most C++ programmers. – Sjoerd Mar 23 '12 at 13:08
  • 1
    @Mankarse The result is undefined, not which conversions are taking place. – Andreas Brinck Mar 23 '12 at 13:09
  • @Mankarse true. However do not look at that, assume they have been properly initializied, it is just about the conversions taking place – Chris Mar 23 '12 at 13:09

2 Answers2

2

Remember the devil is in the details with questions like this, always possible you miss something.

A) Actually I found the answer on stackoverflow(Is if(double) valid C++?): everything in an if is converted directly to boolean.

B) First iVal is converted to float, then added to fVal, and then converted to double. The expression is fully evaluated/typed before the assignment.

C) Left to right order will be applied to the + operators. So iVal is converted to double, then added to dVal and then the same happens with cVal, so directly to double.

Community
  • 1
  • 1
Thirler
  • 20,239
  • 14
  • 63
  • 92
2

a) fval is contextually converted to bool.


In cases b and c, the "usual arithmetic conversions" apply, meaning:

b) ival is converted to float and (using a special rule, rather than the "usual arithmetic conversions") fval + ival is converted to double.

c) ival is converted to double, cval is converted to double.

Mankarse
  • 39,818
  • 11
  • 97
  • 141