I am working on a practice exam right now and I came across a write-your-own code problem that I can't figure out.

The question is:

Modify your first function. In addition to returning the greatest value by pass-by-value, you should also sent a true/false value back to main() if the values are the same. Hint: waht variable type would hold a true/false value? How does this value need to be sent to main?

The first function they speak of is:

double greatest (double value1, double value2){

    if (value1 > value2){
        return(value1);
    }
    else {
        return(value2);
    }

}

Oh, and it can be assumed that all function prototypes were defined earlier.

This is what I have so far for the code we actually need to write for the problem:

double greatest (double value1, double value2, bool tf){

    if (value1>value2){
        return(value1);
    }
    else if (value2>value1){
        return(value2);
    }

    if (value1==value2){
        tf = true;
        return(tf);
    }
    else {
        tf = false;
        return(tf);
    }
}

I know this is wrong but I just can't figure out what to do for the life of me :(

Any help/hint/explination would be amazing.

you can only return a value similar to the function's data type
instead of returning a boolean value you could pass by reference the boolean variable to change it's value accordingly

Edited 4 Years Ago by zeroliken: added info

can you do a pass by reference along with a return in a double function?

So would this be correct then?

double greatest (double value1, double value2, bool& tf){

    if (value1 > value2){

        return(value1);
        tf = false;

    } else if (value2 > value1){

        return(value2);
        tf = false;

    } else if (value1 == value2){

        tf = true;

    }     

}

Edited 4 Years Ago by pattmorter: code tags

So would this be correct then?

Close, but remember that return statements immediately exit your funciton, so the way you wrote your code, tf would never be set unless value1 and value2 are equal. You want to swap the returns and the setting of tf.

  1. You call return before tf = false, hence tf = false will never be executed.
  2. When value1 == value2, nothing is returned. Be sure to always return something.

When these are fixed, then it should work.

This article has been dead for over six months. Start a new discussion instead.