3

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;.

2 Answers 2

5

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;
}
Sign up to request clarification or add additional context in comments.

Comments

2

false will be converted to 0 from the draft C++ standard section 4.7 Integral conversions paragraph 4 which says (emphasis mine going foward):

[...]If the source type is bool, the value false is converted to zero and the value true is converted to one.

I think most people would find that odd but it is valid. As for NULL section 4.10 Pointer conversions says:

A null pointer constant is an integral constant expression (5.19) prvalue of integer type that evaluates to zero or a prvalue of type std::nullptr_t. [...]

5 Comments

That's what I had suspected, I was just hoping it would work like a boolean because I used the actual word false. I'll just use a different method. Thank you. NULL would just go to 0 also? Well then. Thank you for the very complete answer.
@ChrisVachon well 0 will convert to false and non-zero to true, not totally sure what you are trying to do though.
I'm actually trying to go the other way around. I'm supposed to return an int but return the value false.
is it actually possible to return a data type that is different from return type declared in function prototype in c++ ? it is possible in c (in turboC at least)
Using false or NULL will return 0 ... HOWEVER there is no way to tell either of those translated zeros from an actual zero result. if zero is a valid legitimate return value, then you may be getting a false sense of security from using keywords NULL or false.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.