75860

# what does the colon do in c?

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.

`?` is a conditional operator:

```a = b > 0 ? 3:1; ```

is equivalent to:

```if(b > 0) a = 3; else a = 1; ```

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

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 ```

```a = b > 0 ? 3:1; ```
```if(b > 0) a = 3; else a = 1; ```