Wednesday, August 17, 2022

[FIXED] Why variable, passed to a function by reference, doesn't immediately change its value?

Issue

So here is the code (the program calculates the area of ring with specified outter and inner radiuses, nothing too special):

#include <iostream>

bool f(double ro, double ri, double &s) 
{
    const double eps = 1e-12;
    if (ro > ri + eps) 
    {
        const double pi = acos(-1);
        //s = pi * (ro * ro) - pi * (ri * ri);
        s = pi * (ro + ri) * (ro - ri);
        return true;
    }
    return false;
}

int main()
{
    double s = 0;
    double ro, ri;  
    std::cin >> ro >> ri;
    std::cout << f(ro, ri, s) << ' ' << s << '\n'; 
    std::cout << s;
}

The question is, why, for example, for input 5 4 the output will be

1 0
28.2743

, not

1 28.2743
28.2743

?


Solution

Order of evaluation rules have evolved, in particular, in C++17 for E1 << E2.

std::cout << f(ro, ri, s) << ' ' << s << '\n';

is guaranteed to be evaluated in expected order (left to right for E1 << E2 ) in C++17 whereas it was unspecified before.



Answered By - Jarod42
Answer Checked By - Mary Flores (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.