What is the meaning of the == sign?

Am I trying to figure out what the == symbol means in this program?

int main() { int x = 2, y = 6, z = 6; x = y == z; printf("%d", x); } 
+7
c operators syntax
source share
8 answers

The == operator checks equality. For example:

 if ( a == b ) dosomething(); 

And in your example:

 x = y == z; 

x is true (1) if y is equal to z. If y is not equal to z, x is false (0).

A common mistake made by new C programmers (and a typo made by some very experienced ones):

 if ( a = b ) dosomething(); 

In this case, b is assigned and then evaluated as a Boolean expression. Sometimes a programmer does this on purpose, but it is a bad form. Another programmer reading the code will not know if this was done intentionally (rarely) or unintentionally (much more likely). The best design:

 if ( (a = b) == 0 ) // or != dosomething(); 

Here b is assigned a, then the result is compared with 0. The goal is clear. (Interestingly, I worked with C # programmers who never wrote pure C and could not tell you what it does.)

+20
source share

This is the equal operator.

In the above example, x assigned the result of an equality expression ( y == z ). So, if y is equal to z , x will be set to 1 (true), otherwise 0 (false). Since C (pre-C99) is not a boolean, the expression evaluates to an integer.

+5
source share

Equality. It returns 1 if the operands are equal, 0 otherwise.

+4
source share

== means โ€œhas a value ofโ€œ equals. "This operator has higher priority than the = (equal) operator. So, the equation x = y == z; will try to assign the result y == z to the variable x. which in this case is 1 .

+2
source share
 int main() { int x = 2, y = 6, z = 6; x = y == z; printf("%d", x); } 

let's start like this:

  x = (6==6) 

Does it ask for 6 equivalents of 6 ?: true

x = true, but since x is int, x = 1 The new value of x is 1.

The following is printed:

one

+1
source share

Speaking

X will be either true / 1 or false / 0.

Another way to look at this line:

 x = ( is y equal to true? then true/1 or false/0 ) 
0
source share
Operator

== used for equality. here, for example, if y is equal to z, then x will be the true value, otherwise x will be false false

0
source share

Think of it this way:

= means something meaning.

== means that it is equal to the value.

for example

 int val = 5; //val is 5 //= actually changes val to 3 val = 3; //== Tests if val is 3 or not. //note: it DOES NOT CHANGE the value of val. val == 3; int new_val = val == 3; //new_val will be 1, because the test is true //the above statement is the same as bool is_val_3 = false; if( val == 3 ) is_val_3 = true; int new_val; new_val = is_val_3; //putting it together, val = new_val == 2; //sets val to 0. do you understand why now? 
0
source share

All Articles