2

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;
user981245
  • 39
  • 3

4 Answers4

3

?: 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.

ouah
  • 142,963
  • 15
  • 272
  • 331
  • 1
    More commonly known as the ternary operator. – Peter C Mar 16 '12 at 03:34
  • It is called a ternary operator, not "conditional". See http://en.wikipedia.org/wiki/%3F: –  Mar 16 '12 at 03:36
  • 2
    @VladLazarenko The C standard actually calls it "the conditional operator", although I agree that "ternary" is more common. – Timothy Jones Mar 16 '12 at 03:45
  • 2
    @VladLazarenko I removed your changes on my answer. I wrote *conditional operator* on purpose. This is the name of this operator in C. The fact that it is also a ternary operator (even the only ternary operator in C) is a quality of the operator, but the standard name is *conditional operator* (see C99, 6.5.15 Conditional operator). – ouah Mar 16 '12 at 05:34
2

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".

Joey
  • 344,408
  • 85
  • 689
  • 683
Peter C
  • 6,219
  • 1
  • 25
  • 37
2

? is a conditional operator:

a = b > 0 ? 3:1;

is equivalent to:

if(b > 0)
    a = 3;
else
    a = 1;
sirgeorge
  • 6,331
  • 1
  • 28
  • 33
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.

Timothy Jones
  • 21,495
  • 6
  • 60
  • 90