Here is my code snippet:
int a;
if(a=8)
开发者_JS百科 cout<<"Its right";
else
cout<<"Not at all";
getch();
return(0);
I'm getting the output Its right
while I've not give any input there its just a assignment to the a=8
.
**Borland Compiler**
gives the following 2 warnings and executes the code.
1: Possible incorrect assignment (a=8)
2: 'a' is assigned a value that is never used.
When you write:
if(a=8)
You're assigning 8 to the variable a, and returning a, so you're effectively writing:
a = 8;
if(a)
This is non-zero, and hence treated as "true".
I (and the compiler) suspect you intended to write (note ==
instead of =
):
if(a==8)
This is why you get the warnings. (Note that, in this case, a
is still uninitialized, so the behavior is undefined. You will still get a warning, and may still return true...)
a = 8
assign 8
to a
and returns the value of the assignment, that is 8
. 8
is different from 0 and thus is considered true
. the test apsses, and the program outputs "Its right"
.
you may have written if ( a == 8 )
which correctly tests the value of a
without changing its value.
if(a=8)
implies assign a value of 8 to a and then use it to evaluate for the if statement. Since 8 is nonzero it essentially translates to TRUE (any value that is non-zero is true).
The first warning is because it's a frequent typo to write =
in a condition test where you meant ==
. The philosophy behind the warning is that it's a lesser burden for a programmer to rewrite if(a=b)
to, say if((a=b)!=0)
in the few cases he wants that, than to spend frustrating hours debugging the results if he mistakenly got an assignment instead of a comparison.
The second warning is just what it says: It looks like a mistake to have a local variable that you assign a value to but never use.
Since they are just warnings, you're free to ignore them if you think you know what you're doing. The compiler may even provide a way for you to turn them off.
Everyone else's answer is correct :)
if (a = 8) // Sets a to be 8 (and returns true so the if statement passes)
if (a == 8) // Check to see if a is equal to 8
I just want to add that I always (force of habit!) write if statements this way :
if (8 == a) {
Now, if I miss out one of the =
, the compiler doesn't give me a warning, it gives me an error :)
You need a == (double equals). Single = is an assignment; when treated as an expression as you have done here, it evaluates to the value assigned, in this case 8. 0 is treated as False and anything else is True, so (a=8) == 8 == True.
精彩评论