What is more idiomatic for setting a variable value conditionally?

Question

I see a few ways of doing this, but I don't know which one would be easier to understand or more idiomatic in C:

Maybe this: int value; if (a) value = 23; else value = 79;

Or this int value = a ? 23 : 79;

Or maybe this int value = 23; if (a) value = 79;

If condition 'a' were to be named override_value, I'd be more inclined to use the third option much rather than the first.

This looks much better int value = 23; if (override_value) value = 79;

Than this:

int value;
if (!override_value)
    value = 23;
else
    value = 79;

Or this:

int value;
if (override_value)
    value = 79;
else
    value = 23;

How would you do it?

Posted Jul 17, 2024, 6:50 AM UTC

813

Comments aren't archived yet

This post had 13 comments on Reddit. Comments for this period haven't been loaded into the archive yet.