Evaluation order of comma operator

M

mr.gsingh

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
 
G

Gavin Deane

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,961
Messages
2,570,131
Members
46,689
Latest member
liammiller

Latest Threads

Top