Chris
Chris

Reputation: 193

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

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

Upvotes: 3

Views: 8289

Answers (2)

George T
George T

Reputation: 708

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

Upvotes: 5

Shafik Yaghmour
Shafik Yaghmour

Reputation: 158459

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. [...]

Upvotes: 2

Related Questions