[Solved] why printf is not printing here?


Why here the output is only “hie” and “hola”?

Order of precedence of Logical AND (&&) is greater than Logical OR (||). Agreed. But, it doesn’t mean that a program has to evaluate in that order. It just says to group together the expressions. Hence,

if(printf("hie")|| printf("hello")&& printf("nice to see you"))

is equivalent to,

 if(printf("hie")  ||  (printf("hello")&& printf("nice to see you")) )

Short circuit evaluation of ‘||‘ operator happens:

[C11: ยง6.5.14/4] Unlike the bitwise | operator, the || operator guarantees left-to-right evaluation; if the second operand is evaluated, there is a sequence point between the evaluations of the first and second operands. If the first operand compares unequal to 0, the second operand is not evaluated.

So, hie gets printed first and returns a non-zero-value, satisifies the || condition, followed by if condition returning true.


More about order of precedence and order of evaluation :

One of the answers, states that

Order of evaluation does not depend on precedence, associativity, or (necessarily) on apparent dependencies.

Though this is closer but this is not completely true. Though precedence is not the same thing as order of evaluation. There are cases wherein the precedence indirectly influences the order of evaluation.

Consider,

1 + 2 * 3

It is obvious that, order of precedence of * is higher than +. When two operators share an operand, precedence dives into picture, and the operand is grouped with the operator with the highest precedence. In the above statement * and + share the same operand 2, precedence tells that multiplication operator is applied to 2 and 3. + is applied to 1 and the result of multiplication. So, compiler parses the above statement as,

1 + (2 *3)

The constraint on the order of evaluation of above expression is that, addition can’t be completed without the result of multiplication. So, in this case, multiplication(higher precedence) is evaluated before addition(lower precedence)


In your if() statement, precedence tells to compiler to parse the statement in such a way that it has an implicit paranthesis enclosing 2nd and 3rd printf(). That doesn’t mean those has to be evaluated first as explained earlier.

So, we have seen two cases. In one, precedence doesn’t control/influence order of evaluation and in other precedence had an indirect influence.

__

In short

“While precedence may influence the order of evaluation, it doesn’t determine the order of evaluation”

6

solved why printf is not printing here?