Hi,
I am trying to figure out what == sign means in this program?
int main()
{
int x = 2, y = 6, z = 6;
x = y == z;
printf("%d", x);
}
Hi,
I am trying to figure out what == sign means in this program?
int main()
{
int x = 2, y = 6, z = 6;
x = y == z;
printf("%d", x);
}
Equality. It returns 1 if the operands are equal, 0 otherwise.
It is "equals" operator.
In the above example, x
is assigned the result of equality test (y == z
) expression. So, if y
is equal to z
, x
will be set to 1
(true), otherwise 0
(false). Because C (pre-C99) does not have a boolean type, the expression evaluates to an integer.
The ==
operator tests for 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 novice C programmers (and a typo made by some very experienced ones as well) is:
if ( a = b )
dosomething();
In this case, b is assigned to a then evaluated as a boolean expression. Sometimes a programmer will do this deliberately but it's bad form. Another programmer reading the code won't know if it was done intentionally (rarely) or inadvertently (much more likely). A better construct would be:
if ( ((a = b) == 0 ) // or !=
dosomething();
Here, b is assigned to a, then the result is compared with 0. The intent is clear. (Interestingly, I've worked with C# programmers who have never written pure C and couldn't tell you what this does.)
==
is the equality operator. If the arguments (y
, z
in your case) are the same, it will give 1, and 0 otherwise.
You can see a list of C operators here.
It's saying
X will equal either true/1 or false/0.
another way to look at that line is this:
x = ( is y equal to true? then true/1 or false/0 )
== means "is euual to". This operator has higher precedece than = (equal to) operator. So the equation x = y == z; will try to assign result of y==z to variable x. which is 1 in this case.
== operator used for equality.. here in u r example if y is equal to z then x will hav true value otherwise x will hav false
Think about it like this:
= means give something a value.
== means check if it is equal to a 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?