简体   繁体   中英

Conditional operators error

I'm having trouble understanding why the following section of code is returning x and not b.

#include <iostream>

using namespace std;

int main()
{
    int x = 12;
    int a = 1;
    int b = 0;

    cout << "answer: " << (x < a && 1 ? a : (x > b && 0 ? b : x)) << endl;
    return 0;
}

My working is:

  • x is NOT lower than a [logical and) 1, move to second set of brackets.

  • x IS larger than both 0 [logival and] 0 there fore the result should be 'b'.

    (as both statement equate to true, shouldn't the Result_if_true statement be the output?)

x > b && 0 does not mean "x is larger than both b and 0".

Instead, it means: "x is larger than b, and 0 is a true statement". The && operator is a logical AND that connects two statements. You cannot use it in the loose way in which the word "and" is used in natural language.

(x < a && 1 ? a : (x > b && 0 ? b : x))

is parsed as

((x < a) && 1) ? a : (((x > b) && 0) ? b : x)

which is the same as

(false && true) ? a : ((true && false) ? b : x)

ie

false ? a : (false ? b : x)

ie

x

In this expression

(x < a && 1 ? a : (x > b && 0 ? b : x)) 

there is at first evaluated condition

x < a && 1

It is equal to false because x is not less than a.

So the next expression that will be evaluated is

(x > b && 0 ? b : x)

In this expression condition

x > b && 0

is obviously equal to false

So the value of the whole expression will be the value of subexpression

x

and there will be outputed

answer: 12

Your logical mistake is that expression

x > b && 0

is not equivalent to

( x > b ) && ( x > 0 )

it is equivalent to

( x > b ) && ( 0 )

As expression

( 0 )

is equal to false then and

( x > b ) && ( 0 )

is equal to false

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM