7

I have some old-style casting in some c++ code which I would like to convert to new-style. I had a look to precedence and associativity operators documentation, but I failed to understand it.

( double ) myValueA() / myValueB()

is equivalent to

static_cast<double>( myValueA() ) / myValueB()

or to

static_cast<double>( myValueA() / myValueB() )

I suppose the answer will the same for other numerical operators (*/+-)

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
Denis Rouzaud
  • 2,412
  • 2
  • 26
  • 45
  • 5
    See [operator precendence](https://en.cppreference.com/w/cpp/language/operator_precedence). Casting has one of the highest precedent, higher than division and other arithmetic operations. – François Andrieux Sep 19 '18 at 16:46
  • sorry, will reformulate – Denis Rouzaud Sep 19 '18 at 16:48
  • @FrançoisAndrieux can you detail? – Denis Rouzaud Sep 19 '18 at 16:50
  • 1
    [explicit type conversion](https://en.cppreference.com/w/cpp/language/explicit_cast) resolves to a series of cast *as needed*. If `myValueA()` returns a value for which `static_cast` would be sufficient, it's correct to view the `(double)` as one. It would only be a `reinterpret_cast` if the cast wasn't possible with `static_cast`. Also note that explicit type conversion can remove `const` which neither `reinterpret_cast` nor `static_cast` can do. So some explicit type conversions may also require a `const_cast` as part of the series. – François Andrieux Sep 19 '18 at 16:52
  • Also note that _function call_ operator has higher precedence than _C-style cast_ operator. (BTW, its kind-of misleading that we say "higher precedence", but in the table referenced by @FrançoisAndrieux, the precedence has actually lower number). – Daniel Langr Sep 19 '18 at 18:22
  • Same question (for plain C): https://stackoverflow.com/q/3354446/94687 – imz -- Ivan Zakharyaschev Sep 15 '19 at 01:47

2 Answers2

11

In

( double ) myValueA() / myValueB()

( double ) is a c-style cast. If we look at the operator precedence table we will see that it has a higher precedence than the arithmetic operators so

( double ) myValueA() / myValueB()

is the same as

static_cast<double>(myValueA()) / myValueB()
NathanOliver
  • 171,901
  • 28
  • 288
  • 402
6

The cast has higher precendence, so it is equivalent to

static_cast<double>(myValueA()) / myValueB()
Parker Coates
  • 8,520
  • 3
  • 31
  • 37