Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ - Returning "false" in an int returning function

Tags:

c++

null

return

I have an int function that searches an array for a value, and if the value is found it returns the value of the position in the array. If the value isn't found, I simply put return false; Would that give me the same result as return 0;? I would also like to know what exactly would happen if I did return NULL;.

like image 871
Chris Avatar asked Aug 23 '26 09:08

Chris


1 Answers

Unlike PHP and other languages, C++ types aren't changed on the fly. A way to do what you want (return false if something didn't work but return an int if it did) would be to define the function with a return type of bool but also pass an int reference (int&) in it. You return true or false and assign the reference to the correct value. Then, in the caller, you see if true was returned and then use the value.

bool DoSomething(int input, int& output)
{
    //Calculations here
    if(/*successful*/)
    {
        output = value;
        return true;
    }

    output = 0; //any value really
    return false;
}

// elsewhere
int x = 5;
int result = 0;

if(DoSomething(x, result))
{
    std::cout << "The value is " << result << std::endl;
}
else
{
    std::cout << "Something went wrong" << std::endl;
}
like image 190
George T Avatar answered Aug 25 '26 00:08

George T



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!