By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,247 Members | 1,224 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,247 IT Pros & Developers. It's quick & easy.

Evaluation order of comma operator

P: n/a
My program looks something like this:

int x = 23;
if ( (func(x), func1(x), func2(x)) <= (foo(x), foo1(x), foo2(x)))
{
std::cout << "............";
}
else
{
std::cout<< "..............";
}

where func(x), func1(x) and func2(x) return reference to 'x' and foo(),
foo1() and foo2() return integer. I understand this is bad programming
but I am doing this to understand the execution semantics of comma
operator.

g++ gives me the follwoing execution order:

Function foo.
Function foo1.
Function func.
Function func1.
Function func2.
Function foo2.

This looks weird to me. I was expecting s'thing like

func, func1, func2, foo, foo1, foo2

Any explanations for this behavior will be highly appreciated.

Thanks
Gagan

Dec 15 '06 #1
Share this Question
Share on Google+
1 Reply


P: n/a

mr*******@gmail.com wrote:
My program looks something like this:

int x = 23;
if ( (func(x), func1(x), func2(x)) <= (foo(x), foo1(x), foo2(x)))
{
std::cout << "............";
}
else
{
std::cout<< "..............";
}

where func(x), func1(x) and func2(x) return reference to 'x' and foo(),
foo1() and foo2() return integer. I understand this is bad programming
but I am doing this to understand the execution semantics of comma
operator.

g++ gives me the follwoing execution order:

Function foo.
Function foo1.
Function func.
Function func1.
Function func2.
Function foo2.

This looks weird to me. I was expecting s'thing like
It's one allowed possibility.
func, func1, func2, foo, foo1, foo2
That's another allowed possibility.
Any explanations for this behavior will be highly appreciated.
The compiler is required to evaluate the left-hand operand of the comma
operator before the right hand. So in your code, foo(x) must be
evaluated before foo1(x), which must be evaluated before foo2(x). And
similar for func(x), funx1(x) and func2(x). Other than that there is no
requirement or guarantee on the order of evaluation of your functions.
So

foo, foo1, foo2, func, func1, func2
would be equally acceptable.

foo, foo1, func, func2, foo2, func1
would not be allowed. But only because func2 happens before func1.
Everything else about that order is possible.

Gavin Deane

Dec 15 '06 #2

This discussion thread is closed

Replies have been disabled for this discussion.