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));
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
.