PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, August 17, 2022

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

 August 17, 2022     c++, output     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

1,257,709

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © 2025 PHPFixing