Home > Backend Development > C++ > How Does Argument Evaluation Order Affect `std::cout` Output in C ?

How Does Argument Evaluation Order Affect `std::cout` Output in C ?

Susan Sarandon
Release: 2025-01-01 10:45:11
Original
1027 people have browsed it

How Does Argument Evaluation Order Affect `std::cout` Output in C  ?

Order of Evaluation in std::cout Arguments

The order of evaluation of arguments passed to std::cout can be confusing, especially when one or more arguments is a function call that modifies the value of another argument.

Code Example

Consider the following C 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;
}
Copy after login

Unexpected Output

When executed, this code produces the following output:

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

This output may seem surprising, as one might expect the value of test to be 1 after the foo function is called.

Explanation

The order of evaluation of arguments in std::cout is not specified by the C standard, except for a few specific cases such as logical operators (&&, ||) and the ternary operator (? :).

In this example, the compiler is free to evaluate the arguments in any order it chooses. In this case, the foo function is evaluated first, modifying the value of test to 1.0. However, the value of test stored in the std::cout statement is still 0.0, because the std::cout statement is evaluated before the foo function is called.

Solution

To ensure the desired order of evaluation, the code should be rewritten as follows:

std::cout << "Value of test before function call: " << test << std::endl;
foo(test);
std::cout << "Value of test after function call: " << test << std::endl;
Copy after login

This ensures that test is evaluated before and after the foo function call, producing the expected output:

Value of test before function call: 0
Value of test after function call: 1
Copy after login

The above is the detailed content of How Does Argument Evaluation Order Affect `std::cout` Output in C ?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template