I'm confused about this code.

Apr 24, 2010 at 5:26pm
Hello, I'm a little bit confused about this code:
1
2
3
4
5
6
7
8
9
10
11
int fx(int a)
{
// do something
}
int main()
{
int x,y;

fx((x,y)); // <------

}

At first I thought that fx() will be called twice but it's not. And why does this compile anyway?
Thanks for help.

Apr 24, 2010 at 5:35pm
You need to read up on the comma operator

(I'm a fan, some other posters here seem to be afraid of it)
Apr 24, 2010 at 5:41pm
You can find info on that operator in this page: http://www.cplusplus.com/doc/tutorial/operators/
Apr 24, 2010 at 6:00pm
This can be made even more confusing than I thought
1
2
3
4
5
6
7
8
9
10
11
12
13
int fx(int a)
{
return a*2;
}
int main()
{
int x=3,y=10;

fx( ((((y=1+x,x=11),(y=3,x=4)),y=5),((y=6,(x=7,y=8)),(x=9,(y=10,x=11))))); // hahaha ... ???


cout <<"x: "<<x<<endl<<"y: "<<y<<endl;
}


But are there any situations when this can be useful?
Last edited on Apr 24, 2010 at 6:01pm
Apr 24, 2010 at 6:18pm
But are there any situations when this can be useful?


yes, to have fun on forums like this :-)
Apr 24, 2010 at 9:15pm
As anything, it's useful when used properly
Apr 24, 2010 at 9:54pm
As anything, it's useful when used properly


Can you illustrate any situtation in which this would be useful? I can't for the life of me imagine any situation where it would do anything other than obfuscate code.

I'm not doubting that it's useful, I just doubt my ability to see it's usefullness.
Apr 24, 2010 at 10:03pm
One use can be in fors, below is an example

1
2
3
4
5
6
7
void reverse_string ( char *str )
{
    for ( char *a = str, *b = str+strlen(str)-1; a < b;
            a++, b--  // Here
        )
        std::swap ( *a, *b );
}
Topic archived. No new replies allowed.