Lacks in theory and knowledge of „how does compiler works” can be very painful. Simple thing: functions argument evaluation order. We write from left to right, but how does a computer read it? The same way, as we wrote? Or maybe inversely? The C++ Documentation gives a clear answer: it is unknown.
5.2.2 Function call
8 The order of evaluation of arguments is unspecified. All side effects of argument expression evaluations take effect before the function is entered. The order of evaluation of the postfix expression and the argument expression list is unspecified.
It’s unknown, but in fact – we know. Almost all implementations of C/C++ (excluding CLang) are using right to left order. Quite confusing for somebody, who doesn’t know what stack is. How it’s working in practice?
Imagine that we have a text file with positions and sizes of few rectangles:
rect_x rect_y rect_width rect_height
200 200 50 50
Now, we are loading data from file to our scructure:
Rect rect(file.getToken(), file.getToken(), file.getToken(), file.getToken());
And here we are: we have a bug and we will probably spend next three hours thinking why values are in bad order. The compiler reads arguments from right to left, so last getToken() is evaluated as first. Correct code will look something like this:
for(int i = 0; i < 4; i++)
data[i] = file.getToken();
Rect rect(data, data, data, data);
It’s true-life story, from three yeas ago, when I was writing map-editor for a simple game. From that time I’m paying more attention to theory and every day before going to bed, I’m am reading few pages of C++ documentation in front od Bjarne Stroustrup altar. Cheers!