Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the correct way to return an 'Invalid Value' type in C++, without the use of pointers?

I often use -1 as the invalid value type when returning from a function, where the input yields incorrect output. For instance, writing an indexing function where the index is out of bounds, instead of throwing an exception, -1 can be returned. But when writing a function that has negative values as possible return types, this technique does not work. What is the correct way to return an invalid type value in such instances?

The technique I use mostly is to set the return type to be of type *int, and return a Pointer to NULL. But, that requires all return values to be of a pointer type, which seems like an extra overhead to the function. Is there an accepted standard for returning values in such cases?

like image 584
sparkonhdfs Avatar asked Jun 29 '16 14:06

sparkonhdfs


People also ask

Which of the following is correct about this pointer in C ++?

Which of the following is true about this pointer? Explanation: The 'this' pointer is passed as a hidden argument to all non-static member function calls and is available as a local variable within the body of all non-static functions.

How do I find the value of a pointer?

To get the value pointed to by a pointer, you need to use the dereferencing operator * (e.g., if pNumber is a int pointer, *pNumber returns the value pointed to by pNumber .

How do you store a pointer value in a variable?

To store the address of int variable var , we have the pointer to int ptr_var . We would need another pointer to store the address of ptr_var . Since ptr_var is of type int * , to store its address we would have to create a pointer to int * .


1 Answers

In newer C++, I'd suggest using std::optional<>; if you don't yet have it, boost::optional<>.

like image 55
lorro Avatar answered Oct 24 '22 00:10

lorro