Why is my data in the console displayed in the wrong sequence?
I have the following code:
#include <iostream>
template <typename T, typename T2>
T2 printArr(const T* array, int i) {
for (int j = 0; j < i; j ) {
std::cout << array[j] << " ";
}
std::cout << std::endl;
return array[i - 1];
}
int main() {
const int iSize = 3;
int i_arr[iSize] = {23, 45, 78};
std::cout << "Int array: ";
std::cout << "Last element: " << printArr<int, int>(i_arr, iSize) << std::endl;
}
What do I get by compiling it:
Int array: 23 45 78
Last element: 78
What should I get in my opinion:
Int array: Last element: 23 45 78
78
Most likely, I do not understand how the computer that compiles my code thinks.
Here you can see that the result is the same as I described in my question: http://cpp.sh/2lfbcf
And I also try to compile the code in Visual Studio 2019
and the result is identical
CodePudding user response:
Before C 17, given an expression E1 << E2
, it is unspecified whether every value computation and side-effect of E1 is sequenced before every value computation and side effect of E2.
In your code, using a standard before C 17, it is unspecified whether the return value of printArr()
is calculated (which as a side-effect, streams to std::cout
) before or after std::cout << "Last element: "
.