I'm confused about this code.

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.

You need to read up on the comma operator

(I'm a fan, some other posters here seem to be afraid of it)
You can find info on that operator in this page: http://www.cplusplus.com/doc/tutorial/operators/
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
But are there any situations when this can be useful?


yes, to have fun on forums like this :-)
As anything, it's useful when used properly
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.
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.