I was given this example in class and I am unsure what it does. I understand the colon adds a bit-field, but I am still uncertain about this question:
a = b > 0 ? 3:1;
I was given this example in class and I am unsure what it does. I understand the colon adds a bit-field, but I am still uncertain about this question:
a = b > 0 ? 3:1;
?:
operator is called the conditional operator.
If b
value is > 0
, the value 3
is assigned to a
else the value 1
is assigned to a
.
Take your Kernighan & Ritchie book 2nd edition, chapter 2.11 Conditional expressions, the behavior of the operator is explained.
This is the conditional operator. It's equivalent to:
if (b > 0)
a = 3;
else
a = 1;
Read it as "a = if b > 0 then 3 else 1".
?
is a conditional operator:
a = b > 0 ? 3:1;
is equivalent to:
if(b > 0)
a = 3;
else
a = 1;
It's the conditional operator (generally called the ternary operator), which is used as a short way of writing if statements.
In general, it can be read:
condition ? value_if_true : value_if_false
So, in your case:
a = b > 0 ? 3:1;
Can be rewritten as:
if(b > 0) a = 3;
else a = 1;
The colon in this example doesn't mean anything related to bit fields - it's just the second part of the conditional.