I am trying to figure out what =开发者_Python百科= sign means in this program?
int main()
{
int x = 2, y = 6, z = 6;
x = y == z;
printf("%d", x);
}
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.)
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.
Equality. It returns 1 if the operands are equal, 0 otherwise.
== 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.
int main()
{
int x = 2, y = 6, z = 6;
x = y == z;
printf("%d", x);
}
let`s start like this:
x = (6==6)
It asks is 6 equivalent to 6?: true
x = true, but since x is an int, x= 1 The new value of x is 1.
The following is printed:
1
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 )
== 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?
精彩评论