Strange output, not as expected

[亡魂溺海] 提交于 2019-12-01 01:43:30

What you've just found is a classic example of one of the quirks of C++. Your program can actually be decomposed into this simple example:

int i = 10;
f(i, ++i);

The compiler has the choice of function argument evaluation from left-to-right, but this is not guaranteed. Here's some standard text:

5.2/4 Postfix Epressions [expr.post]

When a function is called, each parameter shall be initialized with its corresponding argument. [Note: Such initializations are indeterminatly sequenced with respect to each other (1.9) - end note]

Because they are indeterminatly sequenced, the compiler has the freedom of evaluating ++i before the first argument and initializing it with the corresponding function parameter, and then evaluating i and initializing it with its respective parameter next.

The reason function call argument evaluation ambiguity is applicable here is because operator<<() is a function but it's just being called with the operator syntax. For example, this is what your code looks like if we use the operator-id syntax:

std::operator<<(std::operator<<(std::operator<<(std::cout, "(").operator<<(i*3), ",").operator<<(j*7), ")").operator<<(getRemainderOf(i*3, 7*j, quotient)).operator<<(quotient);

These are just chains of function calls with arguments and they obey the same rule as the one above.

The solution is to sequence the act of modifying the object and using it in the operator<<() call. You already achieved this with partitioning the operator<<() call into two statements with the semicolon ;, so the function is guaranteed to be called before quotient is printed.

The order of evaluation of function arguments is unspecified. In these statements

cout << "("<< i*3 << "," << j*7 << ") "  <<( getRemainderOf(i*3, 7*j, quotient) ) << " " << quotient <<endl;

cout << "("<< i*7 << "," << j*3 << ") "  << getRemainderOf(i*7, 3*j, quotient) << " "; cout << quotient <<endl;

there are called overloaded operators << that are in fact functions. You have to split each statement in two statements. For example

cout << "("<< i*3 << "," << j*7 << ") "  <<( getRemainderOf(i*3, 7*j, quotient) ) ;
cout << " " << quotient <<endl;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!