Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does (0 && 1 == 0) not evaluate to true?

In my if statement, the first condition for && is 0 (false), so the expression 0 && (a++) is equal to 0, right? Then 0==0 it should be true. Why am I getting else here? Please explain!

int a=0;
if(0 && (a++)==0)
{
    printf("Inside if");
}
else
{
    printf("Else");
}
printf("%i",a);
like image 698
Spark Avatar asked Sep 03 '21 16:09

Spark


People also ask

Why is 0 factorial and 1 factorial equal?

The Definition of a Zero Factorial This still counts as a way of arranging it, so by definition, a zero factorial is equal to one, just as 1! is equal to one because there is only a single possible arrangement of this data set.

What is a factorial of 0?

Factorial of a number in mathematics is the product of all the positive numbers less than or equal to a number. But there are no positive values less than zero so the data set cannot be arranged which counts as the possible combination of how data can be arranged (it cannot). Thus, 0! = 1.

What does 0 mean in math?

Zero is the integer denoted 0 that, when used as a counting number, means that no objects are present. It is the only integer (and, in fact, the only real number) that is neither negative nor positive. A number which is not zero is said to be nonzero. A root of a function is also sometimes known as "a zero of ."


Video Answer


2 Answers

The == operator has a higher priority than the && operator, so this line:

if(0 && (a++)==0)

is treated like this:

if(  0 && ((a++)==0) )

So the whole expression under the if is false, and a++ is not even evaluated due to short circuitry of the && operator.

You can read about Operator Precedence and Associativity on cppreference.com.

When in doubt, you should use parenthesis to express your intention clearly. In this case, it should be:

if( (0 && (a++)) == 0  )

Though, it does not make any sense, as it always evaluates to true and a++ is not incremented here, either.

like image 147
Slava Avatar answered Nov 11 '22 06:11

Slava


As already mentioned, the precedence of == is higher than precedence of &&, so the statement is resolved into

if( 0 && ((a++)==0))

However, still even if you add the correct order of brackets, a++ returns the original value of a, which is 0, but the a is incremented. If you want to return the updated value of a, you should write ++a

if( ((++a) && 0) == 0  )
like image 36
Karen Baghdasaryan Avatar answered Nov 11 '22 05:11

Karen Baghdasaryan