Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to test for equivalence of several variables in C

Tags:

c

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?

like image 602
Fergus Avatar asked Dec 22 '09 17:12

Fergus


People also ask

How do you know if variables are equal to multiple values?

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.

How do you test multiple variables for equality against a single value?

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': ...

How do you know if three variables are equal?

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.

Can we compare two variables in C?

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.


3 Answers

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.

like image 192
John Bode Avatar answered Sep 28 '22 09:09

John Bode


if (x1 == x2 && x1 == y1 && x1 == y2)
{
  printf("Input values shouldn't be equal!");
}
like image 24
Sani Singh Huttunen Avatar answered Sep 28 '22 08:09

Sani Singh Huttunen


if( x1 == x2 && x2 == y1 && y1 == y2 ) { ... }
like image 29
Khaled Alshaya Avatar answered Sep 28 '22 08:09

Khaled Alshaya