Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

explicit/implicit type conversion c++

I have a line of code

double i = 1 + (long)1.5* 5.0f

My question is what is the conversion order and the result? Been searching for examples like this, but to no avail. Any good guides out there that may help me understand it?

like image 642
user1601401 Avatar asked Mar 23 '23 05:03

user1601401


2 Answers

My question is what is the conversion order and the result?

The cast is applied to 1.5, giving a long with value 1.

That's converted to float for multiplication with 5.0f, giving a float with value 5.0f.

1 is converted to float for addition with that value, giving a float with value 6.0f.

Finally, that's promoted to double (retaining the value 6.0) to assign to i.

This assumes a non-crazy floating point format that can represent small integers exactly; otherwise, there may be rounding errors.

If you wanted to cast the result of the multiplication, then use parentheses to control the operator precedence:

double i = 1 + (long)(1.5* 5.0f);  // = 8.0

or use a C++-style cast, which forces the use of parentheses:

double i = 1 + static_cast<long>(1.5* 5.0f)

Any good guides out there that may help me understand it?

Here's one: http://en.cppreference.com/w/cpp/language/operator_precedence. Note that the type cast has a higher precedence than multiplication, which is in turn higher than addition (3 vs. 5 vs. 6).

like image 190
Mike Seymour Avatar answered Apr 06 '23 08:04

Mike Seymour


As you can see from this table, the cast operator has higher precedence than multiplication, but follow the advice to use parentheses.

like image 40
Nicola Musatti Avatar answered Apr 06 '23 08:04

Nicola Musatti