Question

I would like to simplify the following expression (block is an integer, either 0 or 1):

if (block)
    opts = opts & ~O_NONBLOCK;
else
    opts = opts | O_NONBLOCK;

This is what I've come up with:

opts = block ? opts & ~O_NONBLOCK : opts | O_NONBLOCK;

I'm sure, however, that there's a much clever way to do that.

Was it helpful?

Solution

How about this?

opts = (opts & ~O_NONBLOCK) | (!block * O_NONBLOCK);

I do prefer the explicitness of your first option over this somewhat cryptic solution, though.

OTHER TIPS

Your first example is about as simple as it could possibly be, and certainly is better at explaining what's going on.

If for some reason you're desperate to type fewer characters, you could use assignment operators, I suppose:

if (block)
    opts &= ~O_NONBLOCK;
else
    opts |= O_NONBLOCK;

I certainly wouldn't go down the ternary operator route if you can avoid it.

In the first version you can also use compound-assignment versions of the operators

if (block)
    opts &= ~O_NONBLOCK;
else
    opts |= O_NONBLOCK;

:)

Although I'd generally prefer ?: operator over if whenever possible and appropriate. Yet in this specific situation it is hard to say what looks more elegant.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top