Reputation: 32787
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: FALSE Why does this happen? also,what does this given below code mean:
if(num1,num2)
Thanks in advance!
Upvotes: 3
Views: 183
Reputation: 262919
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
).
Upvotes: 3
Reputation: 2491
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.
Upvotes: 1
Reputation: 6400
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)
Upvotes: 0
Reputation: 24140
Upvotes: 2
Reputation: 11637
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.
Upvotes: 2
Reputation: 63805
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.
Upvotes: 0