-1

I found a section of code that shows the following:

int A = 4;
int Z;

Z = (A ? 55 : 3);

Why does the result for Z give 55?

Matteo Italia
  • 123,740
  • 17
  • 206
  • 299
Yorda
  • 9

1 Answers1

4

You seem to have a common misconception about the fact that expressions in conditional statements (if, while, ...) and ternary operations must "look like" a condition, so they should contain a relational/equality/logical operator.

It's not like that. Commonly used relational/equality/... operators don't have any particular relationship with conditional statements/expressions; they can live on their own

bool foo = 5 > 4;
std::cout<<foo<<"\n"; // prints 1

and conditional statements/expressions don't care particularly for them

if(5) std::cout << "hello\n"; // prints hello

if/?/while/... just evaluate the expression, check if the result, converted to bool, is true or false, and act accordingly. If the expression doesn't "looks like" a condition is irrelevant, as long as the result can be converted to bool you can use it in a conditional.

Now, in this particular case A evaluates to 4, which is not zero, so when converted to bool is true, hence the ternary expression evaluates to its second expression, so 55.

Matteo Italia
  • 123,740
  • 17
  • 206
  • 299