double z = ( 1 / 2 ) * ( x + y );

Given double variables x and y, what does the following C++ code do?

double z = ( 1 / 2 ) * ( x + y );

I think it creates a new variable z and initialises it with 0 but I'm not sure
Correct. z = 0.
@OP

Perhaps the question is: I guess you realise why? What could you do so that it isn't 0.0, and gives a more "expected" answer - half of x + y? There are several different options.

Edit:

If one wants to know what code does: Write a small program and execute it.
Last edited on
> I think it creates a new variable z and initialises it with 0 but I'm not sure

If the expression (x+y) evaluates to
anything other than NaN, positive infinity or negative infinity: initialise with 0.0
otherwise: initialise with NaN

If it is an exam question, you may also want to add: if either x or y is uninitialised, the initialisation of z engenders undefined behaviour.

NaN: https://en.wikipedia.org/wiki/NaN

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <limits>

void foo( double x, double y )
{
    double z = ( 1 / 2 ) * ( x + y ) ;
    std::cout << "x==" << x << "  y==" << y << "  (x+y)==" << x+y
              << "  z == (0*" << (x+y) << ") == " << z << '\n' ;
}

int main()
{
    foo( 1.0, 2.0 ) ; // x==1  y==2  (x+y)==3  z == (0*3) == 0

    foo( 0.0/0.0, 1.0 ) ; // x==NaN  y==1  (x+y)==NaN  z == (0*NaN) == NaN

    foo( 1.0/0.0, 1.0 ) ; // x==infinity  y==1  (x+y)==infinity  z == (0*infinity) == NaN

    foo( -1.0/0.0, 1.0 ) ; // x==negative_infinity  y==1  (x+y)==negative_infinity  z == (0*negative_infinity) == NaN

    foo( 1.0/0.0, -1.0/0.0 ) ; // xx==infinity  y==negative_infinity  (x+y)==NaN  z == (0*NaN) == NaN

    const auto huge = std::numeric_limits<double>::max() ;
    foo( huge, huge ) ; // x==<huge>  y==<huge>  (x+y)==infinity  z == (0*infinity) == NaN
}

http://coliru.stacked-crooked.com/a/5a2a1fece5ec560c
Last edited on
it will initialize a new variable into z. Try to learn those rules of c++ as it can lead to errors within your code if you don't. If you are having troubles doing that you can try using some code security program as help. I tend to use checkmarx. Works fine.
Good luck!
Ben.
Topic archived. No new replies allowed.