How this logical operator works? [duplicate] - c

This question already has answers here:
Is short-circuiting logical operators mandated? And evaluation order?
(7 answers)
Closed 1 year ago.
#include<stdio.h>
int main()
{
int a=-10,b=3,c=0,d;
d= a++||++b &&c++;
printf("%d %d %d %d ",a,b,c,d);
}
How above expression is evaluates. I have read preceedence but still i am getting confused. Kindly give me the right solution of this in step by step.

In case of || and && operators the order of evaluation is indeed defined as left-to-right.So, operator precedence rules tell you that the grouping should be
(a++) || ((++b) && (c++))
Now, order-of-evaluation rules tell you that first we evaluate a++, then (if necessary) we evaluate ++b, then (if necessary) we evaluate c++, then we evaluate && and finally we evaluate ||.

I have a feeling this is a homework question, so I'll try to give extra explanation. There are actually a lot of concepts going on here!
Here are the main concepts:
Pre- and post- increment and decrement. ++a increments a before the value is used in an expression, while a++ increments a after the value is used in the expression.
Operator precedence. Specifically, && has higher precedence than ||, which means that the assignment of d should be should be read as d = (a++) || (++b && c++);
Expression evaluation order. The link shows a whole list of evaluation rules for C. In particular, item 2 says (paraphrasing) that for operators || and &&, the entire left side is always fully evaluated before any evaluation of the right-hand side begins. This is important because of...
Short-circuit boolean evaluation, which says that, for operators && and ||, if the value of the left-hand term is enough to determine the result of the expression, then the right-hand term is not evaluated at all.
Behaviour of boolean operators in C. There is no inbuilt boolean type in C, and operators && and || work on integer values. In short, an argument is 'true' if it is nonzero, and false if it equals zero. The return value is 1 for true and 0 for false.
Putting this all together, here is what happens:
After the first line, a is -10, b is 3, c is 0 and d is unset.
Next, the variable d needs to be assigned. To determine the value assigned to d, the left hand term of (a++) || (++b && c++) is evaluated, which is a++. The value USED in the expression is 10, however the value of a after this expression is -9 due to the post-increment.
For the purposes of the boolean operator, the value 10 is true, and therefore value of the || expression is 1. Because of short-circuit evaluation, this means that ++b && c++ is not evaluated at all, so the increments do not happen. Thus we have d = 1.
At the end, the values are: a = -9, b = 3, c = 0, d = 1.
So the program prints out -9 3 0 1.

Related

Evaluating an expression containing logical and increment operators in c

I'm trying really hard to understand how this expression is evaluated in c even though I know the precedence and associativity of operators in c language
int i=-4,j=2,k=0,m;
m = ++i || ++j && ++k;
As far as I know the pre increment operators are evaluated first from left to right the the logical and is then the logical so the I value will be -3 the j value will be 3 the k value will be 1 and for m value its 1 but it seems that I'm mistaken.
I'm studying this for an upcoming exam and ill appreciate any help.
The part that you're possibly missing while trying to understand the logic behind the final values obtained is what is known as short circuiting in C.
A summary of what it is -
if the first operand of the || operator compares to 1, then the second operand is not evaluated. Likewise, if the first operand of the && operator compares to 0, then the second operand is not evaluated.
Going by the above rules, the unary operation on i (++i) returns with 1 and hence the following operands of the || statement are essentially ignored. Therefore, the value of all other variables remains unaffected and m receives the value 1.

Short circuit and operator precedence in C

I know that logical operators in C follow short circuiting but my doubt is that are short circuiting and operator precedence rules not opposing each other. See the below example :
#include<stdio.h>
int main()
{
int a;
int b=5;
a=0 && --b;
printf("%d %d",a,b);
return 0;
}
According to the precedence rules, the highest precedence is of the prefix operator. So --b should be evaluated first and then the && and at last result will be assigned to a. So expected output should be 0 4. But in this case the second operand of && never actually executes and result comes out to be 0 5.
Why precedence rules are not being applied here. Are logical operators exempted from precedence rules? If yes, what other operators show such behavior? And what is the logic behind this behavior?
You're conflating two related but different topics: operator precedence and order of evaluation.
The operator precedence rules dictate how various operators are grouped together. In the case of this expression:
a=0 && --b;
The operators are grouped like this:
a = (0 && (--b));
This has no effect however on which order the operands are evaluated in. The && operator in particular dictates that the left operand is evaluated first, and if it evaluates to 0 the right operand is not evaluated.
So in this case the left side of && which is 0 is evaluated, and because it is 0 the right side which is --b is not evaluated, so b is not incremented.
Here's another example of the difference between operator precedence and order of evaluation.
int val()
{
static x = 2;
x *= 2;
return x;
}
int main()
{
int result = val() + (5 * val());
printf("%d\n", result);
return 0;
}
What will the above program print? As it turns out, there are two possibilities, and both are valid.
In this expression:
val() + (5 * val())
There are no operators that have any type of short circuit behavior. So the compiler is free to evaluate the individual operands of both + and * in any order.
If the first instance of val() is evaluated first, the result will be 4 + ( 5 * 8) == 44. If the second instance of val() is evaluated first, the result will be 8 + (5 * 4) == 28. Again, both are valid since the operands may be evaluated in any order.
Precedence affects how ambiguous expressions are parsed. When there are multiple ways to interpret an expression with several operators, precedence tells us which interpretation is correct. Think of precedence as a mechanism to figure out where the implied parentheses are.
For example in the statement in question there are two valid ways to parse it. If = had higher precedence than && it could be read as:
(a = 0) && --b;
But since && has higher precedence, it's actually interpreted as:
a = (0 && --b);
(Note: Your code's formatting suggests it's the first. Be careful not to mislead!)
Evaluation order is different from precedence. They're related, but independent concepts. After precedence is used to determine the correct parsing of an expression, evaluation order tells us the order to evaluate the operands in. Is it left to right? Right to left? Simultaneous? Unspecified?
For the most part evaluation order is left unspecified. Operators like + and * and << have no defined evaluation order. The compiler is allowed to do whatever it likes, and the programmer must not write code that depends on any particular order. a + b could evaluate a then b, or b then a, or it could even interweave their evaluations.
= and &&, among others, are exceptions. = is always evaluated right to left, and && is left to right with short circuiting.
Here's how evaluation proceeds step-by-step for our statement:
a = (0 && --b), = evaluated right to left
0 && --b, && evaluated left to right with short circuiting
0, evaluates false which triggers short circuiting and cancels the next step
--b, not evaluated due to short circuiting
result is 0
a, variable reference evaluated
a = 0, assignment occurs and overall result is 0
You said that there is no specific order for + and *, but this table shows the order to be left to right. Why so?
The last column of that table is associativity. Associativity breaks precedence ties when we use the same operator twice, or when we use operators with the same precedence.
For example, how should we read a / b / c. Is it:
(a / b) / c, or
a / (b / c)?
According to the table / has left-to-right associativity, so it's the first.
What about chained assignments like foo = bar = baz? Now, assignment has right-to-left associativity, so the correct parsing is foo = (bar = baz).
If this all gets confusing, focus on one simple rule of thumb:
"Precedence and associativity are independent from order of evaluation."
Operator precedence doesn't necessarily tell that an expression gets executed first, it just means that the expression is parsed such that the result of the higher-precedence operation is used in the lower-precedence operation and not the other way around. The actual expressions only get evaluated if they need to!
operator && 's order of evaluation is left to right.
= has lower precedence, in fact only ooperator , has lower precedence than =.
So the expresssion will read a = (0 && --b) being 0 evaluated first given the mentioned order of evaluation.
Since 0 evaluates to false, there is no need to evaluate the second part of the expression because false && true is false, given the first part of the expression is false, the expression will always be false.
If you had || operator the second part of the expression would have to be evaluated.
Operator precedence is not all that plays in the game. There is also order of evaluation. And that mandates that a=0 is evaluated first (evaluation order is from left to right), and then right part after the && is not evaluated at all.
That is how C works.

how do we interpret the `||` and `&&` in an assignment statement? [duplicate]

This question already has answers here:
Evaluation of C expression
(8 answers)
Closed 7 years ago.
I have been coding from a long time though I'm still a student programmer/ I'm usually good at programming but when questions like the one below are asked I get stuck. What will be the output and why of the following program?
int main()
{
int i=4,j=-1,k=0,w,x,y,z;
w=i||j||k;
print("%d",w);
return 0;
}
output:
1
why this result? what does the statement w=||j||k; means?
i || j || k is evaluated from left to right. It does that:
i == 4, which is true, so ORing it with any other value will yield true. That's it1.
The rest of the statement is not evaluated because || and && are short-circuit operators, that is, if in your statement i != 0, neither j nor k will be evaluated because the result is guaranteed to be 1. && works similarly.
That's important to remember if you have something like f() || k(), where k has some side effect like an output to screen or a variable assignment; it might not be executed at all.
The bitwise OR operator | really ORs the bitwise representations of the values instead; it evaluates all its operands.
1 Thanks to #SouravGosh on that!
In your code,
w=i||j||k;
is equivalent to
w= ((i||j) || k);
That means, first the (i||j) will be evaluated, and based on the result (if 0), the later part will be evaluated.
So, in your case, i being 4, (i||j) evaluates to 1 and based on the logical OR operator semantics, the later part is not evaluated and the whole expression yields 1 which is finally assigned to w.
Related quotes, from C11 standard, chapter ยง6.5.14, Logical OR operator
The || operator shall yield 1 if either of its operands compare unequal to 0; otherwise, it
yields 0. The result has type int.
then, regarding the evaluation of arguments,
[...] If the first operand compares unequal to 0, the second operand is
not evaluated.
and regarding the grouping,
[...] the || operator guarantees left-to-right evaluation;
The result of boolean operators yields an int value of 0 or 1.
See 6.5.13 and 6.5.14, paragraph 3.
The [...] operator shall yield 1 [or] 0. The result has type int.

Ambiguous operator precedence, please explain why operator predence is not followed here? [duplicate]

This question already has answers here:
Why does "++x || ++y && ++z" calculate "++x" first, even though operator "&&" has higher precedence than "||"
(11 answers)
Closed 9 years ago.
x = y = z = 1;
z = ++x||++y&&++z;
operator precedence is as follows --
(pre-increment) > && > ||
so answer should be--
1. 2||2 && 2
2. 2||1
3. 1
print x,y,z should be 2,2,1
but, answer is 2,1,1.
Precedence is not the same as order of evaluation. Precedence simply determines what operands and operators belong together. The exact order of evaluation is unspecified except with the logical operators, which are evaluated in strict left-to-right order to enable short-circuiting.
So because && has higher precedence, the variables are first grouped as follows:
(++x) || (++y && ++z)
Then, following left-to-right order, ++x is evaluated. Given that ++x is true, it is known that the entire expression is true. So expression evaluation is short-circuited. (++y && ++z) never gets evaluated. Hence y and z never get incremented.
Expressions with logical operators && and || evaluate left to right:
C99, Section 6.5.14-4 Unlike the bitwise | operator, the || operator guarantees left-to-right evaluation; there is a sequence point after the evaluation of the first operand. If the first operand compares unequal to 0, the second operand is not evaluated.
Since x++ is not zero, the expression short-circuits evaluation of everything to the right of ||, including their side effects. That's why only x++ is evaluated, so x becomes 2. The remaining variables stay at 1, as they should.
There's no sequence point in the expression:
z = ++x || ++y && ++z;
between the pre-increment of z and assignment to z.
So, if the ++z is actually evaluated, that puts you instantly into undefined behaviour territory and anything can happen. You are not permitted to modify the same object twice without an intervening sequence point. Annex C (from C99) lists all the sequence points and the controlling one here is following a full-expression (the entire calculation and assignment).
6.5 Expressions /2 states:
Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be read only to determine the value to be stored.
However, given your initial value of x as 1, the ++z part of the expression is not evaluated, in this particular case. That doesn't make the expression itself any less dangerous since it will invoke UB in the case where the starting point is x == -1 and y != -1.
In this case, the controlling part of the standard is 6.5.14 Logical OR operator /4:
Unlike the bitwise | operator, the || operator guarantees left-to-right evaluation; there is a sequence point after the evaluation of the first operand. If the first operand compares unequal to 0, the second operand is not evaluated.
So, the ++x is evaluated first and, because it evaluates to not-zero, ++y && ++z is never evaluated. x is incremented to 2 and z is set to the "truthy" value of that, or 1, y remains untouched at 1.

&& and || operators [duplicate]

This question already has answers here:
Why does "++x || ++y && ++z" calculate "++x" first, even though operator "&&" has higher precedence than "||"
(11 answers)
Closed 4 years ago.
I came across this code:
int main()
{
int i=1,j=2,k=0,m=0;
m = ++i || ++j && ++k;
printf("%d %d %d %d %d",i,j,k,m);
}
The program returns 2 2 0 1.... Why?
&& has a higher priority than || so ++j && ++k should be evaluated first. Hence I would expect j=3 and k=1. It will return true hence || becomes true so ++i shouldn't be evaluated. But it works other way around.
I would like others to explain to me.
Having higher precedence does not mean it gets evaluated first. It just means it binds tighter. In that example, that expression is equivalent to: ++i || (++j && ++k). What gets evaluated first is ++i because || evaluates left to right. Only if that evaluates to false will ++j && ++k be evaluated because || is short-circuiting.
Actually ++i will be evaluated first. Only if it's false will the right side be evaluated (and in your case it's not).
The fact that "&& has higher priority" relates to precedence (how tightly its operands stick to it) not "whose operands get evaluated first".
Because && is indeed above || in the table, the expression will be interpreted like this:
m = ++i || (++j && ++k)
Short circuit evaluation. If, the left-side of the && is non-zero, only then will the right-hand side be evaluated. Likewise, only if the left-hand side of the || is zero, will the right-hand side be evaluated.
"Higher operator precedence" is not the same as "evaluated first". When you use the short-circuiting operators, they are evaluated left-to-right. The results of any arithmetic will be affected by operator precedence, but that doesn't change the left-t0-right ordering of short circuiting.
The complexity of your example is a good reason for not doing this sort of thing. Even if you figure out the rules and know exactly what it will do, the next programmer to come along and look at the code probably won't.
Basically, || means, "if you have received something which is true, return that, otherwise, return whatever happens afterwards." So, the only thing which is evaluated there is m = (++i != 0). That means "increment i, assign m to the value of i compared to 0, break."
To be more specific, this is what is happening:
i = 1;
i = i + 1;
if( i ) {
m = 1;
}
else { // who cares, this will never happen.
j = j + 1;
if( j ) {
k = k + 1;
m = (k != 0); // 1
}
else {
m = 0;
}
}
In the C language, there are two different issues you need to be aware of: operator precedence and order of evaluation.
Operator precedence determines which operator that gets its operands evaluated first, and also which operands that belong to which operator. For example in the expression a + b * c, the operator * has higher operator precedence than +. Therefore the expression will be evaluated as
a + (b * c)
All operators in the C language have deterministic precedence and they are the same on any compiler.
Order of evaluation determines which operand that gets evaluated first. Note that a sub-expression is also an operand. Order of evaluation is applied after the operator precedence has been determined. If the above a+b*c example has left-to-right order of evaluation, then the operands themselves get evaluated in the order a, b, c. If the operands were for example function calls, then the functions a(), b() and c() would have been executed in that order. All operands in this example need to be evaluated since they are all used. If the compiler can determine that some operands need not be evaluated, it can optimize them away, regardless of whether those operands contain side-effects (such as function calls) or not.
The problem is that order of evaluation of operands is most often unspecified behaviour, meaning that the compiler is free to evaluate either left-to-right or right-to-left, and we cannot know or assume anything about it. This is true for most operands in C, save for a few exceptions where the order of evaluation is always deterministic. Those are the operands of the operators || && ?: ,, where the order of evaluation is guaranteed to be left-to-right. (When using formal C language semantics, one says that there is a sequence point between the evaluation of the left and the right operator.)
So for the specific example m = ++i || ++j && ++k.
The unary prefix ++ operators have the highest precedence, binding the operators i, j and k to them. This syntax is pretty intuitive.
The binary && operator has 2nd highest precedence, binding the operators ++j and ++k to it. So the expression is equivalent to m = ++i || (++j && ++k).
The binary || operator has 3rd highest precedence, binding the operators i++ and (j++ && ++k)= to it.
The assignment operator = has the lowest precedence, binding the operators m and ++i || (++j && ++k) to it.
Further, we can see that both the || and the && operators are among those operators where the order of evaluation is guaranteed to be left to right. In other words, if the left operand of the || operator is evaluated as true, the compiler does not need to evaluate the right operand. In the specific example, ++i is always positive, so the compiler can perform quite an optimization, effectively remaking the expression to m = ++i;
If the value of i wasn't known at compile time, the compiler would have been forced to evaluate the whole expression. Then the expression would have been evaluated in this order:
&& has higher precedence than ||, so start evaluating the && operator.
&& operator is guaranteed to have order of evaluation of operands left-to-right, so perform ++j first.
If the result of ++j is true (larger than zero), and only then, then evaluate the right operator: perform ++k.
Store the result of ++j && ++k in a temporary variable. I'll call it j_and_k here. If both ++j and ++k were positive, then j_and_k will contain value 1 (true), otherwise 0 (false).
|| operator is guaranteed to have order of evaluation of operands left-to-right, so perform ++i first.
If ++i is false (zero), and only then, evaluate the right operator "j_and_k". If one or both of them are positive, the result of the || operator is 1 (true), otherwise it is 0 (false).
m gets assigned the value 1 or 0 depending on the result.
You're seeing logical operator short-circuiting here. If the first part of an || condition is true, then it never evaluates the rest of the expression (because if the first part is a pointer-not-null check you wouldn't want to dereference the pointer in the second part if it's null). Further, since it's in a boolean-result expression the result of ++i is converted back to bool value 1 before being assigned into m.
Avoid this kind of code like the plague, it will only give you debugging nightmares in the short and long term.
Shortcut operators will cause the unnecessary expression components not to be evaluated. Since && has a higher precedence, it would need to be evaluated last if you want to allow the || operator to be able to shortcut the whole expression when ++i evaluates to true. Since this is the case, ++i is the only variable evaluated after the "=".
Precedence and order of evaluation are two different things. Both || and && evaluate their operands left-to-right; precedence doesn't change that.
Given the expression a || b && c, a will be evaluated first. If the result is 0, then b && c will be evaluated.
The order of comparison operators (|| and &&) is more important.
That's why you'd better placed your most important test first.
because || and && short circuit and therefore specify sequence points
Note: this was originally tagged C++ as well, and you get a slightly different answer there as overloaded operators || or && do not short circuit just inbuilt ones

Resources