Home > Backend Development > C++ > How Does C 's `std::cout` Evaluate Arguments, and Why Does Order Matter?

How Does C 's `std::cout` Evaluate Arguments, and Why Does Order Matter?

DDD
Release: 2025-01-05 08:18:43
Original
565 people have browsed it

How Does C  's `std::cout` Evaluate Arguments, and Why Does Order Matter?

Order of Argument Evaluation in std::cout

Understanding how function arguments are evaluated in C is crucial to avoid surprises in your code. In the context of std::cout, the evaluation order of arguments can be confusing, as illustrated in the following example:

#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;
}
Copy after login

This code may appear to print the value of test before and after calling the foo function. However, the output suggests otherwise:

Value of test is :      1       Return value of function is : 1 Value of test : 0
Copy after login

This behavior is due to the unspecified order of evaluation in an expression. While it might seem intuitive for the argument farthest to the right (the value of test) to be evaluated first, this is not guaranteed.

To ensure the desired evaluation order, explicitly split the expression into separate statements, as shown below:

double value = test;
std::cout << "Value of test is : \t" << value << "\tReturn value of function is : " << foo(test) <<  "\tValue of test : " << test << std::endl;
Copy after login

This ensures that the value of test is copied into value before the foo function is called. As a result, the output now accurately reflects the expected order of evaluation:

Value of test is :      0       Return value of function is : 1 Value of test : 1
Copy after login

The above is the detailed content of How Does C 's `std::cout` Evaluate Arguments, and Why Does Order Matter?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template