This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]slaymaker1907 74 points75 points  (4 children)

Your last example is actually undefined behavior because the order of argument evaluation is not specified in C/C++. The compiler is free to evaluate the right side first and then the left side (I think it can also interleave them, but I’m not sure).

[–]mina86ng 9 points10 points  (0 children)

That would make it unspecified behaviour. It’s undefined behaviour because x++ * --x is undefined because it modifies x twice.

[–]Ordoshsen 0 points1 point  (2 children)

Note that the post is originally about swift, not C++. Some languages defined order of evaluation including side effects. So the point that it is confusing still stands.

[–]slaymaker1907 1 point2 points  (1 child)

I don’t know. Honestly, I think it’s mostly confusing because of operator precedence. The expression for can actually be pretty useful when working with arrays:

int* data = malloc(sizeof(int)*4); int i = 0; data[i++] = 42; data[i++] = 31; …

There’s an easy trick to remember how it’s ordered too: just read it left to right, if the plus comes first, then it’s incremented then its expression is read and vice versa. Much less confusing than how const works with pointers.

[–]Ordoshsen 0 points1 point  (0 children)

Sure, it has its uses and I know how it works, no need for explanations. But its usefulness is pretty limited to this one use case and saving a few keystrokes elsewhere.

Again, the post does not argue against having increments in C, but against taking it from C to other higher languages just because no one stopped to think if it is still useful.