-2

I'm not used to using brace initialization, but I figured I'd start porting my code over since it's been in the standard since c++11.

One question arises: Is the following expression correct?

double MyFunction(double a,double b,int c)
{
    double dx{(a-b)/c};
    //do things to dx
    return dx;
}

I am initializing a double, dx, using brace initialization which is based on a mathematical expression of a 'double' subtraction and an integer division. This just feels wrong though, like it may produce undefined behaviour. Is the above function 'correct' and will it return the value expected without truncation?

Alternatively, I could try double dx{(a-b)/double(c)}; or double dx = (a-b)/(double(c));

curiousguy
  • 8,038
  • 2
  • 40
  • 58
Arlington
  • 79
  • 1
  • 11
  • 7
    What about it makes you think it has undefined behavior? – NathanOliver Jan 14 '19 at 14:51
  • 6
    "_and an integer division_" There's no integer division in the code shown. Since one of the operands is `double`, `double` division is performed. – Algirdas Preidžius Jan 14 '19 at 14:53
  • 2
    I still argue against using this syntax, it just is uncommon. A good ol' `double dx = (a - b) / c` works the same way, but just looks more natural. – SergeyA Jan 14 '19 at 15:00
  • 1
    this question would be much more clear if you stated why you think there is undefined behaviour or something gets truncated and why you think writing `double dx{(a-b)/double(c)};` would fix either of the two – 463035818_is_not_an_ai Jan 14 '19 at 15:12
  • My confusion was primarily with whether c++ would treat the division by 'c' as double or whether it would narrow. I was pretty sure it was safe, but couldn't find any specific examples of this. – Arlington Jan 14 '19 at 17:31

2 Answers2

3

double dx{(a-b)/c}; is fine. The expression

(a-b)/c

has the type double on the left hand side of the division and int on the right hand side of the division. Through the usual arithmetic conversions the int on the right hand side is converted to a double to match the left hand side and then the division takes place. That means the you're really dividing a double by a double.

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
1

This just feels wrong though

Then feel free to not do it. Copy initialisation is still in C++11 and isn't going anywhere.

like it may produce undefined behaviour

If c==0, then behaviour will be undefined indeed (as far as standard is concerned. For most real compilers though, floating point division by zero is not UB). Otherwise no.

Is the above function 'correct'

The expression is well formed (if it weren't your compiler would be required to tell you), and it has well defined behaviour (possibly with the precondition that c!=0).

and will it return the value expected without truncation?

Depends on what you expect.

eerorika
  • 232,697
  • 12
  • 197
  • 326