0

I have a technical question regarding the ternary operation in C. Let's assume we have the following program:

#include <stdio.h>
#define M(a, b) (b? (a / b) : (a + b))
int main()
{
   int x = 10, y = 3;
   printf("%d\n" , M(x + y , x - y));
}

in the macro, what is the meaning of the question b? Also , I know that the final answer is 7, but how is it 7?

Thomas Dickey
  • 51,086
  • 7
  • 70
  • 105
Integrity
  • 23
  • 3
  • `b ?` means if `b` is true, i.e. if `b != 0`. In this case do division, otherwise perform addition – Dmitry Bychenko Aug 25 '21 at 10:22
  • you'll want parenthesis: `(b)?`, which would be equivalent to `(10-3)?` aka your idea of `7?...`. That said it's a conditional expression, and for integers this evaluates the "truthiness" of the value, aka non-zero – Rogue Aug 25 '21 at 10:22
  • Does this answer your question: https://stackoverflow.com/questions/463155/how-does-the-ternary-operator-work ? – Jabberwocky Aug 25 '21 at 10:23
  • Also be aware that `M(X, Y)` is textually subsituted before the actual compilation: so the compiler sees this: `(x -y ? (x + y / x - y) : (x + y + x - y))` – Jabberwocky Aug 25 '21 at 10:25

2 Answers2

3

It is not the "question b", that is the syntax of ternary operator

expr ? true_expr : false_expr

In your case, after macro substitution your code really becomes

int main()
{
   int x = 10, y = 3;
   printf("%d\n" , (x - y? (x + y / x - y) : (x + y + x - y));
}

Since x - y is 7, this becomes true because it is not 0. true_expr executes next which is (x + y / x - y) in your case. Substituting values, this evaluates to 10 + 3 / 10 - 3 => 10 + 0 - 3, which reduces to 7.

Tanveer Badar
  • 5,438
  • 2
  • 27
  • 32
0

Ternary operator is shorter version of if-else

return (b? (a / b) : (a + b)

would be

if (b)
{
   -> a/b
}
else
{
   -> a+b
}

Generaly, ternary operator looks like this: (expression ? if_expression_is_true : else)

So b? is just b expression