Home >Backend Development >C++ >Why is std::cout Argument Evaluation Order Unpredictable in C ?

Why is std::cout Argument Evaluation Order Unpredictable in C ?

Susan Sarandon
Susan SarandonOriginal
2024-12-26 15:46:26349browse

Why is std::cout Argument Evaluation Order Unpredictable in C  ?

Evaluating Arguments in std::cout Insertion Order

In C , the order of argument evaluation in expressions using the std::cout insertion operator can be confusing. 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;
}

The output of this code is surprising:

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

Understanding this output requires delving into the order of argument evaluation.

Unspecified Evaluation Order

Typically, C doesn't specify the evaluation order of arguments in an expression. This is up to the compiler to decide. However, there are some exceptions, such as:

  • Sequence points introduced by certain operators, such as && and ||
  • The ternary operator

Left-to-Right Evaluation Assumption

It's common to assume left-to-right evaluation for std::cout insertions, but this is not guaranteed. In our example, the "shadowed" test in the third argument is evaluated before the call to foo, which modifies it.

Resolving the Confusion

To ensure the intended evaluation order, split the expression into separate statements:

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

This code correctly outputs:

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

The above is the detailed content of Why is std::cout Argument Evaluation Order Unpredictable in C ?. 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