What is the name of this C++ functionality?
I was writing some C++ code and mistakenly omitted the name of a function WSASocket
. However, my compiler did not raise an error and associated my SOCKET
with the integer value 1 instead of a valid socket.
The code in question should have looked like this:
this->listener = WSASocket(address->ai_family, address->ai_socktype, address->ai_protocol, NULL, NULL, WSA_FLAG_OVERLAPPED);
But instead, it looked like this:
this->listener = (address->ai_family, address->ai_socktype, address->ai_protocol, NULL, NULL, WSA_FLAG_OVERLAPPED);
Coming from other languages, this looks like it may be some kind of anonymous type. What is the name of the feature, in the case it is really a feature?
What is its purpose?
It's difficult to search for it, when you don't know where to begin.
Solution 1:
The comma operator† evaluates the left hand side, discards its value, and as a result yields the right hand side. WSA_FLAG_OVERLAPPED
is 1, and that is the result of the expression; all the other values are discarded. No socket is ever created.
† Unless overloaded. Yes, it can be overloaded. No, you should not overload it. Step away from the keyboard, right now!
Solution 2:
The comma operator is making sense of your code.
You are effectively setting this->listener = WSA_FLAG_OVERLAPPED;
which just happens to be syntatically valid.
Solution 3:
The compiler is evaluating each sequence point in turn within the parenthesis and the result is the final expression, WSA_FLAG_OVERLAPPED
in the expression.
The comma operator ,
is a sequence point in C++. The expression to the left of the comma is fully evaluated before the expression to the right is. The result is always the value to the right. When you've got an expression of the form (x1, x2, x3, ..., xn) the result of the expression is always xn
.