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;.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With