PengYu.UT@gmail.com wrote:[color=blue]
> I used comma expression in two different ways in the following code.
> This code is reduced from some more complex code. I don't have the
> ability to write in the 2nd way for the complex code.
>
> I want the output of the 2nd is wanted. Do you have any idea how to
> modify the 1st way such that it gives the same output as the 2nd one?
>
> Thanks,
> Peng
>
> #include <iostream>
>
> class plot {
> public:
> plot &doit(int &i){
> std::cout << i << std::endl;
> return *this;
> }
> };
>
> int main ()
> {
> plot p;
> int i = 10;
> p.doit((++i,i)).doit((++i,i));// output 12 12; 1st way; not wanted
> std::cout << std::endl;
> i = 10;
> p.doit((++i,i));
> p.doit((++i,i)); // output 11 12; 2nd way different from above
> }[/color]
Have a look at this
http://www.gotw.ca/gotw/056.htm
If you imagine
p.doit((++i,i)).doit((++i,i));
as the compiler sees it (like a normal function, with the object's this
pointer passed as an extra parameter) you get
doit( &(doit(&p, (++i, i))), (++i, i) );
I think that, despite your use of the comma operator to introduce a
sequence point between ++i and i each time, the fact that the
evaluation of function arguments can happen in any order and can be
interleaved means that you still have undefined behaviour. The second
++i can start before the first one has finished.
http://www.parashift.com/c++-faq-lit...html#faq-39.15
I have stared at your code for quite a while and I'm not 100% sure of
my answer. If I'm wrong, hopefully someone will correct me.
Gavin Deane