Am I getting weird output in C?

Here is the c program. I get a strange conclusion.

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();
}

Conclusion: TRUE

when num1 = 0 and num2 = 220 Conclusion: TRUE

But when num1 = 0 and num2 = 0: Conclusion: FALSE Why is this happening? also, which means this below under the code:

if(num1,num2)

Thanks in advance!

+3
source share
6 answers

You are using a comma operator . This operator first evaluates its first operand, then discards the result to the floor and continues to evaluate and return its second operand.

That's why your program prints only FALSEif num2assessed as FALSEin a boolean context (eg 0, 0.0or NULL).

+3

:

if(num1,num2)

, :

if(num2)

num2 0, FALSE.

, http://msdn.microsoft.com/en-us/library/2bxt6kc4(v=vs.71).aspx a, , , , - num2.

+2
+2
if(num1,num2)

. Comma , . , (a, b) a, b, b.

, b.

+1
if(num1,num2)

is not a syntax error, but it is a logical error. In principle, this will only be decided

if(num2)

Only the last variable is calculated.

0
source

I suppose you want "if a and b are true." Such a comma, like you, uses tools to evaluate only the last variable.

I think you want:

if(num1 && num2) /* num1 AND num2 */

You need to use && (logical AND) not one and (which is bitwise AND)

0
source

Source: https://habr.com/ru/post/1791818/


All Articles