Operators

Pages: 12
So, if the functions are called in a defined order, why does it not work if a, b, and c were a, a, and a? What if it were the same function with a parameter to express either a, b, or c?
Last edited on
If you have two function calls in the same expression you can not rely on in which order they are called. This code can print "ab3" or "ba3" but this has not much to do with the problem we discussing here.
1
2
3
4
5
6
7
8
9
#include <iostream>

int a(){std::cout<<"a";return 1;}
int b(){std::cout<<"b";return 2;}

int main()
{
	std::cout << a() + b();
}
Last edited on
Mainly because the expression a++ can do the increment at any time before a ',' ';' '&&' '||' or '?:'.
@Peter87: Caligulaminus claims the functions are evaluated in a defined order, and I am now very confused....
What exactly are you confused about?
The table you linked to is straight forward.

P.S. Not I am claiming that. The C++ standard defines it so. I'm simply telling you (as rocketboy does).
@L B
http://www.cplusplus.com/doc/tutorial/operators/
In the table I see this:
2 ++ postfix Left-to-right
3 ++ unary (prefix) Right-to-left
3 + unary sign operator Right-to-left

Why is this information wrong?


The information is correct, but grouping (shown in the table you reference) and evaluation order (what the question is about) are completely different things.

Grouping (and operator precedence) is a parsing rule. It says that x=b++ + ++b + b++ is parsed as if it was x = ( ( (b++) + (++b) ) + (b++) ). It says nothing about evaluation order.

The C++ (and C) compiler has no restrictions (except when && and friends are used) on the order of evaluation of subexpressions as long as their results are collected and ready when the function/operator call is made. They can be left to right, right to left, interleaved, and can change expression to expression, let alone compiler to compiler. There is no telling, when evaluating each of these three 'b's, how many increments have already taken place.

As a practical demo, original program (with syntax errors fixed) in different compilers produces

gcc 4.6.2 linux: 18 25 36 14
gcc 3.4.6 sparc: 17 19 24 9
clang 3.0 linux: 19 28 37 14
intel c 11.1 linux: 18 27 36 14
Sun C++ 5.8 sparc: 20 28 39 14
Sun C 5.8 sparc: 18 27 36 14
Last edited on
Topic archived. No new replies allowed.
Pages: 12