Say I wanted to test not just one, but several variables for equivalence in an if statement:
if(x1==x2==y1==y2){
printf("Input values shouldn't be equal!");
}
But this doesn't seem to work. What other approach can do this?
To check if a variable is equal to all of multiple values, use the logical AND (&&) operator to chain multiple equality comparisons. If all comparisons return true , all values are equal to the variable. Copied! We used the logical AND (&&) operator to chain multiple equality checks.
If you have the opposite case and you have multiple variables you need to check against one value, you can swap the left and right sides of the in operator. So instead of using or operators like this: >>> a, b, c = 3.1415, 'hello', 42 >>> if a == 'hello' or b == 'hello' or c == 'hello': ...
To have a comparison of three (or more) variables done correctly, one should use the following expression: if (a == b && b == c) .... In this case, a == b will return true, b == c will return true and the result of the logical operation AND will also be true.
Comparing two integer variables is one of the simplest program you can write at ease. In this program, you can either take input from user using scanf() function or statically define in the program itself. We expect it to be a simple program for you as well. We are just comparing two integer variables.
if (x1 == x2 && x2 == y1 && y1 == y2) { ... }
The result of the expression a == b
will be an integer value of either 0 or 1. the ==
operator is left-associative, so the expression a == b == c
will be evaluated as (a == b) == c
; that is, the result of a == b
(0 or 1) will be compared against the value of c. So in the code below
if (a == b == c) { ... }
the expression will only evaluate to true if a == b and c == 1 or a != b and c == 0.
if (x1 == x2 && x1 == y1 && x1 == y2)
{
printf("Input values shouldn't be equal!");
}
if( x1 == x2 && x2 == y1 && y1 == y2 ) { ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With