In following function I'm trying find a node in Binary tree that matches the key. I'm passing reference node pointer as smart pointer and this function returns a refernce to node pointer.
How can I return NULL ? As the return value of function is std::unique_ptr<node>& so it is supposed to return a reference.
std::unique_ptr<node>& BST::ReturnNodePrivate(const int& key, std::unique_ptr<node> &ptr){
if(NULL != ptr){
if(ptr->key == key){
return ptr;
}
}
else{
return NULL;
}
}
How can I return NULL ?
Return NULL in C++ - C++ Forum
How do I return a Null Pointer in a function C++ - Stack Overflow
c++ - returning NULL pointer in C - Stack Overflow
How to return an invalid reference?
Videos
Value of return type std::vector<int> cannot be nullptr.
The most straightforward way in this case is to return std::unique_ptr<std::vector<int>> instead - in this case it's possible to return nullptr.
Other options:
- throw an exception in case of fail
- use
optional<std::vector<int>>as return type (eitherboost::optionalorstd::optionalif your compiler has this C++17 feature) - return
boolparameter and havestd::vector<int>&as output parameter of function
The best way to go really depends on the use case. For example, if result vector of size 0 is equivalent to 'fail' - feel free to use this kind of knowledge in your code and just check if return vector is empty to know whether function failed or succeed.
In my practice I almost always stick to return optional (boost or std, depending on environment restriction).
Such interface is the most clear way to state the fact that 'result can either be present or not'.
To sum up - this is not a problem with the only one right solution. Possible options are listed above - and it's only a matter of your personal experience and environmental restrictions/convetions - which option to choose.
You could return a std::unique_ptr<std::vector<int>> and check that value, or throw an exception, or check vector.size() == 0 etc.
You could use std::find_if algorithm:
Person * lookForName(vector<Person*> &names, const std::string& input)
{
auto it = std::find_if(names.begin(), names.end(),
&input{ return p->getName() == input; });
return it != names.end() ? *it : nullptr; // if iterator reaches names.end(), it's not found
}
For C++03 version:
struct isSameName
{
explicit isSameName(const std::string& name)
: name_(name)
{
}
bool operator()(Person* p)
{
return p->getName() == name_;
}
std::string name_;
};
Person * lookForName(vector<Person*> &names, const std::string& input)
{
vector<Person*>::iterator it = std::find_if(names.begin(), names.end(),
isSameName(input));
return it != names.end() ? *it : NULL;
}
If the name you are searching for is not at the first element, then you are not searching in the rest of the elements.
You need to do something like -
for (int i = 0; i<names.size(); i++){
Person* p = names[i];
if (p->getName() == input) {
return p;
// Placing break statement here has no meaning as it won't be executed.
}
}
// Flow reaches here if the name is not found in the vector. So, just return NULL
return NULL;
As Chris suggested, try using std::find_if algorithm.
NULL is a pointer literal which is defined to contain a special value.
One possible definition is:
#define NULL ((void *)0)
For more detail you can read this faq
About const string& foo(), I believe you mean C++'s std::string.
std::string has no implicit constructor that initialize it with NULL pointer.
So you should use some exception or empty string to indicate an error to the caller. (If you are not throwing, you must return an std::string. Even if the object returned is local, its life is prolonged when kept in a local constant reference. But returning some other type and expecting an implicit conversion is not a good idea.)
Answer to your question: Because NULL is a literal, no temporary object may be created most of the time and actual value can be directly returned to the caller.
This function
const string& foo();
does not return a pointer. It returns a constant reference to an object of type std::string. So its return value may not be assigned to a pointer.
According to the C++ Standard
4.10 Pointer conversions [conv.ptr]
1 A null pointer constant is an integer literal (2.14.2) with value zero or a prvalue of type std::nullptr_t. A null pointer constant can be converted to a pointer type; the result is the null pointer value of that type and is distinguishable from every other value of object pointer or function pointer type. Such a conversion is called a null pointer conversion. Two null pointer values of the same type shall compare equal. The conversion of a null pointer constant to a pointer to cv-qualified type is a single conversion, and not the sequence of a pointer conversion followed by a qualification conversion (4.4). A null pointer constant of integral type can be converted to a prvalue of type std::nullptr_t. [ Note: The resulting prvalue is not a null pointer value. โend note ]
So when you use null pointer constant defined with macro NULL it is assigned to the return pointer of the function that will contain null pointer value of type node *
I think you need something like
CopyNormal* Sphere::hit(Ray ray) {
//stuff is done here
if(something happens) {
return NULL;
}
//other stuff
return new Normal(something, somethingElse);
}
to be able to return NULL;
There are several fairly standard ways of doing this. There are different tradeoffs for the methods, which I'm not going to go into here.
Method 1: Throw an exception on failure.
CopyNormal Sphere::hit(Ray ray)
{
//stuff is done here
if(something happens) {
throw InvalidIntersection;
}
//other stuff
return Normal(something, somethingElse);
}
void example(Ray r)
{
try {
Normal n = s.hit(r);
... SUCCESS CASE ...
}
catch( InvalidIntersection& )
{
... FAILURE CASE ...
}
}
Method 2 return a pointer to a newly allocated object. (You could also use smart pointers, or auto_ptrs to make this a little neater).
CopyNormal* Sphere::hit(Ray ray)
{
//stuff is done here
if(something happens) {
return NULL
}
//other stuff
return new Normal(something, somethingElse);
}
void example(Ray ray)
{
Normal * n = s.hit(ray);
if(!n) {
... FAILURE CASE ...
} else {
... SUCCESS CASE ...
delete n;
}
}
Method 3 is to update an existing object. (You could pass a reference, but a convention I use is that any output parameter is passed by pointer).
Copybool Sphere::hit(Ray ray, Normal* n)
{
//stuff is done here
if(something happens) {
return false
}
//other stuff
if(n) *n = Normal(something, somethingElse);
return true;
}
void example(Ray ray)
{
Normal n;
if( s.hit(ray, &n) ) {
... SUCCESS CASE ...
} else {
... FAILURE CASE ...
}
}
Method 4: Return an optional<Normal> (using boost or similar)
Copyoptional<Normal> Sphere::hit(Ray ray)
{
//stuff is done here
if(something happens) {
return optional<Normal>();
}
//other stuff
return optional<Normal>(Normal(something, somethingElse));
}
void example(Ray ray)
{
optional<Normal> n = s.hit(ray);
if( n ) {
... SUCCESS CASE (use *n)...
} else {
... FAILURE CASE ...
}
}
if( mystruct == NULL )
mystruct is not a pointer, so you cannot compare it with NULL.
You have three options:
- Add a status field to
MyStructto indicate whether the struct has been initialized correctly. - Allocate the struct on the heap and return it by pointer.
- Pass the structure as a pointer argument and return a status code (thanks @Potatoswatter).
A structure is not a pointer. If you want to be able to return NULL, you're going to have to allocate the structure on the heap so you can return a pointer to it, and let the caller clean up afterwards.
That way, you can indicate failure, something like:
MyStruct *init_mystruct (void) {
MyStruct *mystruct = malloc (sizeof (*mystruct));
if (mystruct != NULL)
return NULL;
int is_ok = 1;
/* do something ... */
/* everything is OK */
if( is_ok )
return mystruct;
/* something went wrong */
free (mystruct);
return NULL;
}
int main (void) {
MyStruct *mystruct = init_mystruct();
if (mystruct == NULL) {
/* error handler */
return -1;
}
free (mystruct);
return 0;
}
NULL is a pointer value - or rather a null-pointer value.
NULL means that the function can't find where your pointer should point to - for example if you want to open a file, but it doesn't work your file pointer is returned as NULL. So you can test the value of a pointer and check to see if it worked or not.
If you are writing a routine
int length()
then you could return a negative value if length is unable to read the length of whatever you send it - this would be a way of indicating an error, because normally lengths can never be negative....
It is a matter of convention and you should clearly have one in your head and document it (at least in comments).
Sometimes a pointer really should always point to a valid address (see this intSwap example, both arguments should be valid pointers). At other times, it should either be such a valid address, or be NULL. Conceptually the pointer type is then by convention a sum type (between genuine pointer addresses and the special NULL value).
Notice that the C language does not have a type (or a notation) which enforces that some given pointer is always valid and non-null. BTW, with GCC specifically, you can annotate a function with __attribute__ using nonnull to express that a given argument is never null.
A typical example is FILE* pointers in <stdio.h>. The fopen function is documented to be able to return NULL (on failure), or some valid pointer. But the fprintf function is expecting a valid pointer (and passing NULL to it as the first argument is some undefined behavior, often a segmentation fault; and UB is really bad).
Some non-portable programs even use several "special" pointer values (which should not be dereferenced), e.g. (on Linux/x86-64) #define SPECIAL_SLOT (void*)((intptr_t)-1) (which we know that on Linux it is never a valid address). Then we could have the convention that a pointer is a valid pointer to a valid memory zone, or NULL or SPECIAL_SLOT (hence, if seen as an abstract data type, it is a sum type of two distinct invalid pointers NULL and SPECIAL_SLOT and the set of valid addresses). Another example is MAP_FAILURE as result of mmap(2) on Linux.
BTW, when using pointers in C to heap allocated data (indirectly obtained with malloc), you also need conventions about who is in charge of releasing the data (by using free, often thru a supplied function to free a data and all its internal stuff).
Good C programming requires many explicit conventions regarding pointers, and it is essential to understand them precisely and document them well. Look for example[s] into GTK. Read also about restrict.
The draft C++ standard in appendix C.4 C Standard library which is non-normative says:
The macro NULL, defined in any of <clocale>, <cstddef>, <cstdio>, <cstdlib>, <cstring>, <ctime>, or <cwchar>, is an implementation-defined C++ null pointer constant in this International Standard (18.2).
the respective normative sections agree for example 18.2 says:
The macro NULL is an implementation-defined C++ null pointer constant in this International Standard (4.10).194
which would mean if you are using the those particular headers NULL should be compatible with nullptr and then I would just use nullptr.
In appendix D which covers compatibility does not seem to make a similar statement for .h header files, so although we would expect that NULL and nullptr should be compatible null pointer constants and we would be surprised if they were not from the standard point of view it seems at minimum to be underspecified. Which leaves us with a dilemma, from a practical perspective we are pretty sure they are compatible but we don't have enough information from the standard to prove it.
So I would use NULL as defined by the specific header file you are using or we can use != 0 since fortunately both C99 and C++11 tell us that 0 is a null pointer constant.
From C99 section 6.3.2.3 Pointers:
An integer constant expression with the value 0, or such an expression cast to type void *, is called a null pointer constant.55) If a null pointer constant is converted to a pointer type, the resulting pointer, called a null pointer, is guaranteed to compare unequal to a pointer to any object or function.
and:
Any pointer type may be converted to an integer type. Except as previously specified, the result is implementation-defined
and C++ section 4.10 Pointer conversions tells us:
A null pointer constant is an integer literal (2.14.2) with value zero or a prvalue of type std::nullptr_t. A null pointer constant can be converted to a pointer type; the result is the null pointer value of that type and is distinguishable from every other value of object pointer or function pointer type.[...]
They are exactly and totally equivalent, so use nullptr because NULL is a primitive C-ism that has no reason to live anymore.
But in the case of CreateEventEx you have the hilarious bonus of not all invalid HANDLEs being nullptr, some of them are INVALID_HANDLE_VALUE instead. So neither is really "safe" in the case of HANDLE. You need to check exactly what CreateEventEx returns on failure.