I am getting a strange output in C?
Here is a c program.I am getting a strange output.
When num1=10 and num2=20->
#include<stdio.h>
void main()
{
int num1=10,num2=20;
clrscr();
if(num1,num2)
{
printf("TRUE");
}
else
{
printf("FALSE");
}
getch();
}
Output: TRUE
when num1=0 and num2=220 Output: TRUE
But when num1=0 and num2=0: Output: FAL开发者_JS百科SE Why does this happen? also,what does this given below code mean:
if(num1,num2)
Thanks in advance!
You're using the comma operator. That operator first evaluates its first operand, then drops the result on the floor and proceeds to evaluate and return its second operand.
That's why your program only prints FALSE
if num2
evaluates to false
in a boolean context (like e.g. 0
, 0.0
or NULL
).
In:
if(num1,num2)
the last expression overrides all preceeding ones so it's the same as:
if(num2)
since, num2 is 0, you get FALSE.
If you check this out, http://msdn.microsoft.com/en-us/library/2bxt6kc4(v=vs.71).aspx the , stands for sequential evaluation, meaning the expressions are evaluated one after another, the last being your num2.
- Learn about comma operator in c http://en.wikipedia.org/wiki/Comma_operator. i=(a,b) means store b in i.
- Everything else than 0 in c is true. so if(3) if (-3) all are true only if(0) is false
if(num1,num2)
Is a use of the comma operator. The Comma operator calculates the first operand and discards the result then the second operand and returns the result. Thus (a, b)
calculates a, calculates b and then returns b.
This should clear up your confusion for the logical cases, in each of them the statement has the effect of looking at the value of b.
if(num1,num2)
is not a syntax error, but it is a logic error. Basically, this will resolve to being only
if(num2)
Only the last variable is evaluated.
I assume what you want is 'if a and b are true'. The comma like you are using means to evaluate just the last variable.
What I think you want is:
if(num1 && num2) /* num1 AND num2 */
You need to use && (logical AND) not a single & (Which is bitwise AND)
精彩评论