[try Beta version]
Not logged in

 
succession

Apr 2, 2017 at 4:55pm
I have question to the following exercise:
#include <iostream>
using namespace std;
int main()
{
double a=8, b=9, c=7;

cout << (b=(a=b+0.5)+(c=b));
cout << a/2 << b/2 << c/2;
}

18.54.759.254.5 is the output.

How shall the compiler know which part has to be calculated first (b=(a=b+0.5)
or (c=b)? Shouldn't the succession of these two expressions be undefined?
Apr 2, 2017 at 7:36pm
Hello Bagration1,

Try this it will make the output easier to read:

1
2
3
4
5
6
7
8
9
10
#include <iostream>

int main()
{
	double a = 8, b = 9, c = 7;

	std::cout << (b = (a = b + 0.5) + (c = b)) << std::endl;
	std::cout << "a = " << a << " b = " << b << " c = " << c << std::endl;
	std::cout << a / 2 << " " << b / 2 << " " << c / 2 << std::endl;
}


Starting with (b = (a = b + 0.5) + (c = b)) what you will end up with is (b = (a = 9 + 0.5) + (c = b)) --> (b = (9.5) + (c = 9)) -->(b = 9.5 + 9) --> prints b which = 18.5. After the first line is printed a = 9.5, b = 18.5 and c = 9. c = 9 because b was used before it changed.

The second cout will show what each variable is after the first cout.

Hope that helps,

Andy
Last edited on Apr 2, 2017 at 8:18pm
Apr 2, 2017 at 8:15pm
Hello Bagration1,

An after thought since I did not answer your fully.

When something is in "()" or "[]" they are done first. Then there is the order which could be left to right or right to left depending on the rules:

http://www.cplusplus.com/doc/tutorial/operators/#precedence

When there are more than one "()" in a statement they work from inside out. And in this case it works from left to right.

You may also find this link useful:

http://www.cplusplus.com/forum/beginner/197488/

Hope that helps,

Andy
Apr 11, 2017 at 12:50pm
Thanks! I've totally mixed up the brackets...
Topic archived. No new replies allowed.