简体   繁体   中英

Function of type bool receiving parameter (reference) and possibly return it in C++?

I have a homework task in my university where I should make a function of type bool(double &var) which takes a reference to the variable as a parameter. Then the function performs some calculations and should calculate the result in a new seperate variable, but at the same time return it in the var variable (the parameter of the function). I would like to ask how can this be accomplished? Below is a simple example of the problem:

#include <iostream>
using namespace std;
double rez;
bool func(double &var){
//var = 5;
if(var>3){
    rez = var;
    return var;
}
else{
    return false;
}
}
int main(){

}

When you pass-by-value. like bool func(double var) , what happens is that you get a local var , which will be gone if you leave scope. Imagine something like this: A function

bool func(double var) {
     double res = var * 2;
     return true;
}

called like this:

double someVar = 5;
bool success = func(someVar);

You could calculate with var all you want, when returning from func the local copy var will be gone and you are left with someVar == 5 .

Now, when you pass per reference (ie bool func(double &var) ) everything you do with the passed var will be done to the original one. That means when returning from func you would be left with someVar == 10 . success would be true in either way.

Hope this helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM