When simple arithmetic isn’t so simple!

What could be as simple as incrementing a variable by one? Ignoring overflow, what else could possibly go wrong? As it turns out, quite a lot as this little quiz demonstrates.

Question: What is the value of a and i after this code runs?

int i = 0;
char a[2] = { 0 };
a[i++] = ++i;

Answer: The behaviour of the code in undefined.

Why?

A variable cannot be modified more than once in any expression unless the modification is punctuated with a sequence point. A sequence point (of which there are 6 in standard C++) guarantees that all the side effects of the previous expression are complete and no side effects from sub-sequence expression have been performed. Since i is modified and read twice in this expression the result is undefined.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s