Reputation: 127
I'd like to do the following:
r = recv(socket, buffer, bufsize, 0) && return r;
which doesn't work because return -r;
isn't an expression. However,
r = recv(socket, buffer, bufsize, 0) && printf("r=%d\n", r);
seems to work. Now, there's not a whole lot to gain from this apart from syntactical brevity but I'm still curious if there's a way to accomplish the functionality of && return r;
that actually compiles?
EDIT: If it wasn't clear, the expression after the &&
should be executed if and only if the first one is non-zero.
Upvotes: 0
Views: 89
Reputation: 9213
This is a bad idea but just since you want it, here you go
r = recv(socket, buffer, bufsize, 0) && (({return r;}),0);
This will work as you want.
I can explain what is happening if you need. I repeat it is bad idea.
Apart from being a bad idea this solution uses a gcc extension named - Statement-expressions. So this answer is not portable across compilers.
Upvotes: -1
Reputation: 15813
printf()
is syntactically an expression
(function call) while return __
is a jump-statement
.
The operator &&
requires 2 operands of type expression
, this is why it rejects your code.
Look at Appendix A
in the ISO 9899
.
Upvotes: 2
Reputation: 214880
Yes it is possible.
r = recv(socket, buffer, bufsize, 0);
if (r != 0)
{
return r;
}
If you are searching for something more complicated than that, you are doing it wrong. Good programmers strive for simplicity, bad programmers strive for obfuscation.
Upvotes: 1
Reputation:
the expression after the && should be executed if and only if the first one is non-zero.
And here is your problem: expressions aren't executed, they are evaluated. Statements are executed.
Expressions can have side effects happening during evaluation, but they always evaluate to some value. As you have already learned, return
is a statement and not an expression.
So, in short, no, there's no way for what you want to do.
Upvotes: 8