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

Leave a Reply

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