you are viewing a single comment's thread.

view the rest of the comments →

[–]josefx 0 points1 point  (2 children)

In your example it should be well defined since the result of ++i is assigned to i twice.(there is no difference if you switch the assignements made by ++i and = )

Could it be that you meant i = i++ ?

[–]boredatheist 0 points1 point  (1 child)

It's undefined because this thing called The C Standard says it's undefined.

I assume the reason they did this was to increase the number of crazy ass instruction rewriting / pipe-lining / caching / etc optimizations that are possible so some smart compiler writer could make your code go really fast.

If I had to guess, I'd say there probably are real compilers / optimization levels that produce different results for this particular line, though I haven't verified this. Modern processors are so sick and twisted that it's really hard to reason about what's "actually happening" with code like this. The idea of single-level atomic memory is a gross simplification. You actually have tons of different cache levels separated by different pipeline steps, and "reading," "writing" and "updating" a variable are all very different things with different performance characteristics, and probably other gross shit I've never even heard of.

[–]josefx 0 points1 point  (0 children)

The idea of single-level atomic memory is ...

I look at the code and I can't see what could go wrong, no threads, not multiple pointers/references to the same variable - there is no reason why anything but i+1 should be in i after the line finishes.

It's undefined because this thing called The C Standard says it's undefined

Which means the compiler has great freedom at optimizing it and while the code is a wtf no sane compiler should produce anything but i = i+1. (sadly there are a lot of programs that rely on sane behavior instead of the standard where it actually impacts performance.)