Skip to content

Instantly share code, notes, and snippets.

@pb-uk
Created August 12, 2020 16:01
Show Gist options
  • Save pb-uk/d9b9e30f77cd867d89df947cd3714247 to your computer and use it in GitHub Desktop.
Save pb-uk/d9b9e30f77cd867d89df947cd3714247 to your computer and use it in GitHub Desktop.
Use postfix operators wisely
// It starts innocently enough:
int j = 0;
a = b[j++];
// a now contains b[0] and j is 1.

// Now I want to add a value from another array:
a = b[j] + c[j++];
// But how this works is not defined in the C++ standard, compilers don't even
// have to treat this consistently in different parts of your code!

// How about I want to increment by 2 instead of 1?
a = b[j += 2];
// a now contains b[2], that's not what I wanted.

// Now I want a to be an array;
a[j] = b[j++];
// Oh, now a[1] contains b[0], that's not what I wanted, lets try:
a[j++] = b[j];
// It works now - but only since C++11 so let's hope I never compile this on
// anything older!
// Let's do it properly:
int j = 0;
a = b[j];
j++;
// Just the same as before, and because compilers are better at optimization
// than I am it runs just as quickly.

// Now I want to add a value from another array:
// Change a = b[j]; to
a = b[j] + c[j];
// That works exactly as intended.

// How about I want to increment by 2 instead of 1?
// Change j++; to
j += 2;

// Now I want a to be an array;
// Change a = b[j]; to
a[j] = b[j];

In each case the result works exactly as intended, and it was obvious which statement I needed to change.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment