Author Topic: C: the long and short of it  (Read 6766 times)

0 Members and 2 Guests are viewing this topic.

Offline SiliconWizard

  • Super Contributor
  • ***
  • Posts: 17773
  • Country: fr
Re: C: the long and short of it
« Reply #25 on: June 05, 2020, 01:53:14 pm »
Parentheses in an expression (outside function call parameter list, which lexically is parenthesised) are not a sequence point either, so they are only used in their mathematical sense, and do not define the order in which the compiler must evaluate the subexpressions.  In particular, an expression such as (a*(b-c))*d does not mean that the compiler has to calculate (b-c) first, then multiply it by a, and finally by d; the compiler is free to choose the evaluation order, as long as the math rules are not violated.

Thanks for pointing this out. If I'm not mistaken, I think this is what C99 standard calls "grouping"? And admittedly this part is not the clearest piece of text I've ever read.

As you said though, casting a sub-expression WILL force the compiler to evaluate it as grouped.
So in your example, if you write: '(a*(int32_t)(b-c))*d', for instance, then 'b-c' will be evaluated in this order.

For fixed-point implementation, it is common to cast to a wider type for intermediate values, so using a cast in this context guarantees the order of evaluation.
 


Share me

Digg  Facebook  SlashDot  Delicious  Technorati  Twitter  Google  Yahoo
Smf