Hi guys,
Something has just been bugging me today with regards to part of an implementation of Merge Sort, whereby the merging loop uses the ternary operator. I suddenly had the thought that my code might actually be undefined behaviour. I initially thought it was fine, but now I'm not sure. The line of code in question is:
sortArr[c++] = (rightArr < leftArr[a]) ? rightArr[b++] : leftArr[a++];
The assumption this code makes is that only either rightArr[b++] OR leftArr[a++] is executed.
Now, all is fine and dandy when the second and third expressions used in the ternary operator don't have side effects. E.g.
int foo = (bar == 42) ? 10 : 20;
But can someone check the standard and see if it is possible that in the first example I gave that both a and b might be incremented? It is working as desired in VS2005 Express, but I'm worried that even though only the result of one of those expressions will be assigned to sortArr[c++], that it might actually evaluate both anyway, on a different compiler and increment a and b.
I guess a simpler example that hilights the issue would be:
int foo = (bar == 42) ? a++ : b++;
The reason I'm particularly unsure whether it will execute only one of the side effects is that when using the ternary operator in template meta-programming in the past I've seen evidence that it evaluates both sides.
I've done a bit of a search on the net, but couldn't find anything that goes into enough detail to answer my question. Perhaps I just need some reasusrance.