Xyz
Xyz

Reputation: 63

Reading and interpreting a logical expression in a program

How do you usually read logical expressions in a program? For example:

(1 == x) && ( 2 > x++)? (x=1)

What is the purpose of ? and what is the way of thinking for generating the right answer for the expression?

Upvotes: 2

Views: 198

Answers (4)

Vishwa Ratna
Vishwa Ratna

Reputation: 6400

 (1 == x) && ( 2 > x++)? (x=1);

? stands for ternary operation. , if left of ? is true then it follows immediate right side.

In your case if ( 2 > x++) is true then value of x will be 1. but to travel towards ( 2 > x++) your left expression have to be true which means x==1, so if (1 == x) is true and so( 2 > x++) is true then your overall condition to true.

Upvotes: 1

Garikai
Garikai

Reputation: 425

The following statement:

var value = (boolean expression) ? some value if `true` : some value if `false`

Is a special conditional statement which makes use of a Ternary Operator (?:) to assign values, based on the boolean expression, to the variable.

It's a much more concise way of expressing this conditional statement:

var value;

//this is the boolean expression you evaluate before the question mark
if (boolean expression is true) {
    //this is what you assign after the question mark
    value = some value if true;
}
else {
    //this is what you assign after the colon
    value = some other value if false;
}

So based on your example (syntactically faulty btw), that would be something like:

if ((1 == x) && (2 > x++)){
    x = 1;
}
else {
    /*This is the value that would be put after the colon
     *(which is missing in your example, and would cause a compiler error)
     */
    x = some other value; 
}

Which would translate to:

x = (1 == x) && (2 > x++) ? 1 : some other value

Upvotes: 1

Erwin Smout
Erwin Smout

Reputation: 18408

In addition to the relevant comments about ?: where the colon is required, the following is also needed to "understand" the operation of the code in example :

Evaluation order of && implies that ´ ( 2 > x++) ´ will not be evaluated al all unless ´(1 == x)´ is true. Meaning in particular that the side-effect from x++ will not occur.

´x=1´ is an assignment so at first glance that doesn't look like an expression that evaluates to a value, but in java assignments are themselves expressions that take on the value being assigned.

Upvotes: 1

Schidu Luca
Schidu Luca

Reputation: 3947

This statement does not even compile, ? is used with : as a ternary operator.

After (x=1) you should have the else branch, just an example:

(1 == x) && ( 2 > x++) ? (x=1) : (x = 2)

The way this boolean expression is evaluated is the following, suppose x is 1 :

  1. (1 == x) = true
  2. (2 > x++) = false
  3. true && false = false

You expression will always be false regardless of the value of your x

Upvotes: 1

Related Questions