Unsequenced modification and access

As of this posting, searching Google for the title of this article will provide you with a Link to the patch for the -Wunsequenced flag introduced in C11, but it won’t tell you what this means. So I will.


int letters[15];
int index = 0;
...
if(((letters[index] & 0xF) - (letters[++index] & 0xF)) == 1) {
...

This will produce the warning “Unsequenced modification and access to ‘index'” on the if statement line. Why? Because the ‘-‘ operator is not a sequence point. Basically, the compiler is free to reorder anything and everything until it hits a “sequence point”. Things like return, if, assignment, variable declaration, etc are all sequence points.

But, when the compiler looks at addition (or subtraction), it might decide to evaluate the right side before the left, because subtraction is not a sequence point. This would result in evaluating letters[++index] before letters[index], which is not at all what you expected.

So yes, while this looks completely valid and deterministic read left to right, nobody forced the compiler to read it left to right, and ambiguity resulted. Now you know.

About Bion

I'm a software developer at Modo Payments, a mobile payment provider. When I'm not hacking away the office, you I'm usually at home hacking on something else. Or practicing Aikido. Anyway, I just post things here that Google couldn't help me with, so maybe it'll help you in the future. Since you're reading this, I guess it worked :)
This entry was posted in Technology and tagged . Bookmark the permalink.

2 Responses to Unsequenced modification and access

  1. Steve says:

    Thanks! That saved me a lot of time reading specs. All to easy to forget what the compiler does under the hood.

  2. Pratik says:

    #include
    int main()
    {
    int i=1;
    printf(“%d%d%d”,i++,i,++i);
    return 0;
    }

    Output is unsequenced warning.

Leave a Reply to Steve Cancel reply

Your email address will not be published. Required fields are marked *