Reputation: 119
Disclaimer: I don't code like this, I'm just trying to understand how the c language works!!!!
The output is 12.
This expression (a-- == 10 && a-- == 9)
evaluates left-to-right, and a is still 10 at a-- == 10
but a is 9 for a-- == 9
.
1) Is there a clear rule as to when post-increment evaluate? From this example it seems it evaluates prior to the && but after the ==. Is that because the && logical operator makes a-- == 10
a complete expression, so a is updated after it executes?
2) Also for c/c++, certain operators such as prefix decrement occur right to left so a == --a
first decrements a to 9 and then compares 9 == 9. Is there a reason for why c/c++ is designed this way? I know for Java, it's the opposite (it's evaluates left to right).
#include <stdio.h>
int main() {
int a = 10;
if (a-- == 10 && a-- == 9)
printf("1");
a = 10;
if (a == --a)
printf("2");
return 0;
}
Upvotes: 5
Views: 757
Reputation: 22
The underlying problem is that the postfix unary operator has both a return value (the starting value of the variable) and a side effect (incrementing the variable). While the value has to be calculated in order, it is explicit in the C++ specs that the sequencing of any side effect relative to the rest of the operators in a statement is undefined, as long as it happens before the full expression completes. This allows compilers (and optimizers) to do what they want, including evaluating them differently on different expressions in the same program.
From the C++20 code spec (C++ 2020 draft N4849 is where I got this from):
Every value computation and side effect associated with a full-expression is sequenced before every value computation and side effect associated with the next full-expression to be evaluated. [6.9.1 9, p.72]
If a side effect on a memory location is unsequenced relative to either another side effect on the same memory location or a value computation using the value of any object in the same memory location, and they are not potentially concurrent, the behavior is undefined. [6.9.1 10, p.72]
So, in case you haven't gotten it from other answers:
No, there is no defined order for a postfix operator. However, in your case (a-- == 10 && a-- == 9)
has defined behavior because the && enforces that the left side must be evaluated before the right side. It will always return true, and at the end, a==8. Other operators or functions such as (a-- > a--)
could get a lot of weird behavior, including a==9 at the end because both prefix operators store the original value of a(10) and decrement that value to 9 and store it back to a.
Not only is the side-effect of setting a=a-1 (in the prefix operator) unsequenced with the rest of this expression, the evaluation of the operands of == is also unsequenced. This expression could:
Evaluate a
(10), then evaluate --a
(9), then ==
(false), then set a=9.
Evaluate --a
(9), then a
(10), then set a=9, then evaluate ==
(false).
Evaluate --a
(9) the set a=9, then evaluate a
(9), then evaluate ==
(true)
Yes, it is very confusing. As a general rule (which I think you already know): Do not set a variable more than once in the same statement, or use it and set it in the same statement. You have no idea what the compiler is going to do with it, especially if this is code that will be published open source, so someone might compile it differently than you did.
Side note:
I've seen so many responses to questions about the undefined behavior of postfix operators that complain that this "undefined behavior" only ever occurs in the toy examples presented in the questions. This really annoys me, because it can and does happen. Here is a real example of how the behavior can change that I had actually happen to me in my legacy code base.
result[ctr]=source[ctr++];
result[ctr++]=(another calculated value without ctr in it);
In Visual Studio, under C++14, this evaluated so that result
had every other value of source
in even indexes and had the calculated values in the odd indexes. For example, for ctr=0
, it would store source[0]
, copy the stored value to result[0]
, then increment ctr
, then set result[1]
to the calculated value, then increment ctr
. (Yes, there was a reason for wanting that result.)
We updated to C++20, and this line started breaking. We ended up with a bad array, because it would store source[0]
, then increment ctr
, then copy the stored value to result[1]
, then set result[1]
to the calculated value, then increment ctr
. It was only setting the odd indexes in result
, first from source
then overwriting the source
value with the calculated value. All the odd indexes of result
stayed zero (our original initialization value).
Ugh.
Upvotes: -1
Reputation: 47952
This expression (a-- == 10 && a-- == 9) evaluates left-to-right,
Yes, mostly, but only because &&
is special.
and a is still 10 at a-- == 10
Yes, because a--
yields the old value.
but a is 9 for a-- == 9.
Yes, because the sequence point at &&
guarantees the update to a
's value is complete before the RHS is evaluated.
1) Is there a clear rule as to when post-increment evaluate?
The best answer, I think, is "no". The side effects due to ++
and --
are completed at some point prior to the next sequence point, but beyond that, you can't say. For well-defined expressions, it doesn't matter when the side effects are completed. If an expression is sensitive to when the side effect is completed, that usually means the expression is undefined.
From this example it seems it evaluates prior to the && but after the ==. Is that because the && logical operator makes a-- == 10 a complete expression, so a is updated after it executes?
Basically yes.
2) Also for c/c++, certain operators such as prefix decrement occur right to left
Careful. I'm not sure what you mean, but whatever it is, I'm almost certain it's not true.
so a == --a first decrements a to 9 and then compares 9 == 9.
No, a == --a
is undefined. There's no telling what it does.
Is there a reason for why c/c++ is designed this way?
Yes.
I know for Java, it's the opposite (it's evaluates left to right).
Yes, Java is different.
Here are some guidelines to help you understand the evaluation of C expressions:
Learn the rules of operator precedence and associativity. For "simple" expressions, those rules tell you virtually everything you need to know about an expression's evaluation. Given a + b * c
, b
is multiplied by c
and then the product added to a
, because of the higher precedence of *
over +
. Given a + b + c
, a
is added to b
and then the sum added to c
, because+
associates from left to right.
With the exception of associativity (as mentioned in point 1), try not to use the words "left to right" or "right to left" evaluation at all. C has nothing like left to right or right to left evaluation. (Obviously Java is different.)
Where it gets tricky is side effects. (When I said "'simple' expressions" in point 1, I basically meant "expressions without side effects".) Side effects include (a) function calls, (b) assignments with =
, (c) assignments with +=
, -=
, etc., and of course (d) increments/decrements with ++
and --
. (If it matters when you fetch from a variable, which is typically only the case for variables qualified as volatile
, we could add (e) fetches from volatile
variables to the list.) In general, you can not tell when side effects happen. Try not to care. As long as you don't care (as long as your program is insensitive to the order in which side effects matter), it doesn't matter. But if your program is sensitive, it's probably undefined. (See more under points 4 and 5 below.)
You must never ever have two side effects in the same expression which attempt to alter the same variable. (Examples: i = i++
, a++ + a++
.) If you do, the expression is undefined.
With one class of exceptions, you must never ever have a side effect which attempts to alter a variable which is also being used elsewhere in the same expression. (Example: a == --a
.) If you do, the expression is undefined. The exception is when the value accessed is being used to compute the value to be stored, as in i = i + 1
.
Upvotes: 1
Reputation: 223992
The logical &&
operator contains a sequence point between the evaluation of the first and second operand. Part of this is that any side effect (such as that performed by the --
operator) as part of the left side is complete before the right side is evaluated.
This is detailed in section 6.5.13p4 of the C standard regarding the logical AND operator:
Unlike the bitwise binary & 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 equal to 0, the second operand is not evaluated.
In the case of this expression:
(a-- == 10 && a-- == 9)
The current value of a
(10) is first compared for equality against 10. This is true, so the right side is then evaluated, but not before the side effect of decrementing a
that was done on the left side. Then, the current value of a
(now 9) is compared for equality against 9. This is also true, so the whole expression evaluates to true. Before the next statement is executed, the side effect of decrementing a
that was done on the right side is done.
This expression however:
if (a == --a)
Involves reading and writing a
in the same expression without a sequence point. This invokes undefined behavior.
Upvotes: 3
Reputation: 1301
With "logical and" operator (a-- == 10 && a-- == 9)
is well-formed expression (without undefined behavior as it is in a++ + a++
).
C standard says about "logical and"/"logical or" operators:
guarantees left-to-right evaluation; there is a sequence point after the evaluation of the first operand.
So that, all side effects of the first subexpression a-- == 10
are complete before the second subexpression a-- == 9
evaluation.
a
is 9
before evaluation of second subexpression.
Upvotes: 0