user7893856
user7893856

Reputation: 127

logical operators as conditionals in c

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

Answers (4)

Ajay Brahmakshatriya
Ajay Brahmakshatriya

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

alinsoar
alinsoar

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

Lundin
Lundin

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

user2371524
user2371524

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

Related Questions