Home >Backend Development >C++ >What Determines the Evaluation Order of Arguments in `std::cout`?

What Determines the Evaluation Order of Arguments in `std::cout`?

Barbara Streisand
Barbara StreisandOriginal
2024-12-25 11:44:33523browse

What Determines the Evaluation Order of Arguments in `std::cout`?

Evaluation Order in std::cout

Confusion often arises regarding the order of argument evaluation when using std::cout's insertion operator. Consider the following code snippet:

#include <iostream>

bool foo(double& m) {
    m = 1.0;
    return true;
}

int main() {
    double test = 0.0;
    std::cout << "Value of test is: \t" << test << "\tReturn value of function is: " << foo(test) << "\tValue of test: " << test << std::endl;
    return 0;
}

Surprisingly, the output of this code is:

Value of test is:      1       Return value of function is: 1 Value of test: 0

This violates the imagined left-to-right evaluation order.

Specific reason

In C, the order of evaluation of expression elements is undefined (except for some special cases, such as && and || operators and the introduction of ternary operator for sequential dots). Therefore, there is no guarantee that test will evaluate before or after foo(test) (which modifies the value of test).

Workaround

If the code relies on a specific order of evaluation, the easiest way is to split the expression in multiple separate statements, like this:

std::cout << "Value of test is: \t" << test << std::endl;
foo(test);
std::cout << "Return value of function is: " << foo(test) << std::endl;
std::cout << "Value of test: " << test << std::endl;

This way the order of evaluation will be clearly defined from top to bottom.

The above is the detailed content of What Determines the Evaluation Order of Arguments in `std::cout`?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn