Beruflich Dokumente
Kultur Dokumente
Answered Mar 31, 2018 · Upvoted by Quentin Lassalle, Master Computer Programming & Management,
Paris West University Nanterre La Defense (2018) and Dmitriy Genzel, PhD in CS
https://www.quora.com/What-is-the-difference-between-I-and-I-I-1-in-C-language
Short, simple, useful, but incomplete answer:
If you’re given two separate, complete C statements: i++; and i = i + 1;, both
statements will have the same net effect on the program. Both will add 1 to the value of i.
So, if you see a standalone i = i + 1; or i++ or even ++i;, all three have the same net
effect.
But, that’s not really what you asked.
If you just consider these as expressions yielding a value, you get two unique behaviors out
of the three expressions:
1. #include <stdio.h>
2. #include <stdint.h>
3.
4. int main() {
5. uint8_t i;
6.
7. i = 255;
8. printf("i = 255; i++ = %d\n", i++);
9.
10. i = 255;
11. printf("i = 255; ++i = %d\n", ++i);
12.
13. i = 255;
14. printf("i = 255; (i = i + 1) = %d\n", i = i + 1);
15.
16. return 0;
17. }
The output:
1. int bad1(int i) {
2. return ++i < 42 ? ++i : 42;
3. }
4.
5. int bad2(int i) {
6. return i = i + 1 < 42 ? i = i + 1 : 42;
7. }
In the bad1 case, I believe bad1 is weird, but at least does not invoke undefined behavior.
There is a sequence point between the evaluation of the condition for ?: and the evaluation
of the selected path through ?:.
In the bad2 case, I believe there is not a sequence point between the final evaluation on the
right-hand side and the final assignment to i on the left-hand side. That one takes you
into undefined behavior territory.
So, it’s a mess.
Ultimately, the two don’t differ much in practice. Use what’s most readable to you, or if you
have a set of coding guidelines you need to adhere to for class or $DAYJOB, just adhere to
that wherever it makes sense.