1

I just started classes at my school in programming and I learned how to use ? : for the first time. My first question is what this is called, because my prof didn't say what it is called.

Second, I'm writing a program that prints even when given an even number and odd when given an odd number. I wanted to write it like this

int main() {
    int x = 3;
    char *string;

    if (x % 2 == 0 ? string = "Even" : string = "Odd");

    printf("%d is %s", x, string);
}

the problem is I get an error error: lvalue required as left operand of assignment at if (x % 2 == 0 ? string = "Even" : string = "Odd"); and it's the string = "Odd" part.

Am I not allowed to assign expressions to variables inside of if( ? : )? I want to keep my code short and not have to write it like

if (x % 2 == 0) {
    printf("%d is Even", x);
} else {
    printf("%d is Odd", x);
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
codey
  • 11
  • 2
  • 3
    Don't use it if you don't understand it. A simple if is much more readable. _...what this is called..._ It's called ternary operator. – B001ᛦ Jul 22 '21 at 20:46
  • 1
    You don't use `?:` inside an `if` statement. It's used *instead* of an `if` statement when you want to assign the value to the same variable. – Barmar Jul 22 '21 at 20:46
  • 2
    I figured it out, I literally just wrote ```string = (x % 2 == 0 ? "Even" : "Odd");``` – codey Jul 22 '21 at 20:47
  • 1
    Does this answer your question? [If statement with ? and :](https://stackoverflow.com/questions/20887012/if-statement-with-and) – mkrieger1 Jul 22 '21 at 20:48
  • You can assign inside a conditional, but you need to add parentheses because of the default precedence. – Barmar Jul 22 '21 at 20:48
  • `x % 2 == 0 ? (string = "Even") : (string = "Odd")` – Barmar Jul 22 '21 at 20:48
  • @Barmar You don't actually *need* the first set of parentheses (though it's good to have them). From [cppreference](https://en.cppreference.com/w/c/language/operator_precedence#cite_note-3): *The expression in the middle of the conditional operator (between ? and :) is parsed as if parenthesized: its precedence relative to ?: is ignored.*. – Adrian Mole Jul 22 '21 at 20:53
  • The `if()` instruction doesn't make sense, because its body is an empty instruction (consisting of a semicolon `;` alone). As a result the execution of `if(condition);` is precisely the same as `condition;`, whether the condition expression evaluates as _false_ or _true_.. – CiaPan Jul 22 '21 at 20:59
  • @AdrianMole I believe in thorough use of parentheses in any complex expression like this, rather than depending on remembering the default precedence. – Barmar Jul 22 '21 at 21:01
  • The C standard calls `? :` the conditional operator. It is a ternary operator. It is the only one in C, excluding function calls and `_Generic`, but it is not “the” ternary operator. – Eric Postpischil Jul 22 '21 at 21:03
  • It is called the 'C obfuscation operator' :) – Martin James Jul 23 '21 at 03:05

4 Answers4

3

Don't use the ternary operator to invoke statements within each clause. That is, don't use it as a replacement for if/else. Use it for assignments:

Instead of this:

if (x % 2 == 0 ? string = "Even" : string = "Odd");

This:

string = (x % 2 == 0) ? "Even" : "Odd";
selbie
  • 100,020
  • 15
  • 103
  • 173
  • I *think* the 'formal' name (as per the Standard) is "conditional operator" but the term "ternary operator" is widely used. – Adrian Mole Jul 22 '21 at 20:49
  • Right after I wrote my question, I tried this and it worked. I felt silly after. This is exactly what I was looking for. – codey Jul 22 '21 at 20:50
  • @AdrianMole _ternary_ operator is from how it looks, that is A ? B : C, where A contains the condition. The normal assignment can be called _binray_ operator as well. Yet there are no _quaternary_ and _quintuple_ and so on... – LinconFive Jul 27 '21 at 02:26
2

This operator ?: is called in C the conditional operator. Programmers also call it as the ternary operator because the operator has three operands.

It is defined in C like

conditional-expression:
    logical-OR-expression
    logical-OR-expression ? expression : conditional-expression

The assignment operator has lower priority than the conditional operator.

This conditional operator in the if statement

if (x % 2 == 0 ? string = "Even" : string = "Odd");

is incorrect. In fact it is equivalent to

if ( ( x % 2 == 0 ? string = "Even" : string ) = "Odd" );

If the conditional operator within the if statement will be written correctly like

if (x % 2 == 0 ? string = "Even" : ( string = "Odd" ) );

nevertheless using the if statement itself does not make a sense because the expression within the if statement returns a pointer to a string literal that is not a null pointer. That is this if statement does not have a sub-statement and its condition is always evaluates to logical true.

You need just to write the following statement

x % 2 == 0 ? string = "Even" : ( string = "Odd" );

or for more readability like

x % 2 == 0 ? ( string = "Even" ) : ( string = "Odd" );

or simpler

string = x % 2 == 0 ? "Even" : "Odd";

Pay attention to that there is a difference in the definition of the conditional operator in C and in C++. In C++ the operator is defined like

conditional-expression:
    logical-or-expression
    logical-or-expression ? expression : assignment-expression

As you see the third expression may be an assignment expression. This means that you may write in C++ your conditional operator like

x % 2 == 0 ? string = "Even" : string = "Odd";

without enclosing in parentheses the third operand.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
1

It's called the "conditional operator". Because it's the only most known ternary operator (meaning it takes thee operands) in C and in C++ many people call it ternary operator.

Conditional Operator: ? :

expression ? expression : expression

The conditional operator (? :) is a ternary operator (it takes three operands). The conditional operator works as follows:

The first operand is implicitly converted to bool. It is evaluated and all side effects are completed before continuing.

If the first operand evaluates to true (1), the second operand is evaluated.

If the first operand evaluates to false (0), the third operand is evaluated.

The result of the conditional operator is the result of whichever operand is evaluated — the second or the third. Only one of the last two operands is evaluated in a conditional expression.

The rules for determining the type of the expression are a bit complicated. In simple terms its type is the common type between the second and third operand

bolov
  • 72,283
  • 15
  • 145
  • 224
  • It is not actually the only ternary operator. `(` and `)` used for function calls are an operator, per C 2018 6.5.2, and `foo(a, b)` has three operands. Similarly, `_Generic` is an operator, and `_Generic(foo, int: 0, default: 1)` has three operands. – Eric Postpischil Jul 22 '21 at 21:06
  • @EricPostpischil I had no ideea, but now that I think about it it makes total sense. You learn something every day :) – bolov Jul 22 '21 at 22:55
1

?: is called a ternary or conditional operator.

Last two lines can be merged into a single line like this:

printf("%d is %s\n", x, (x % 2 == 0) ? "Even" : "Odd");

You also don't need the string variable.

user3386109
  • 34,287
  • 7
  • 49
  • 68
Shighil
  • 39
  • 1
  • 7