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).
How to return NULL object in C++ - Stack Overflow
Difference between return 1 and return NULL
function cannot return null in c - Stack Overflow
Can you return NULL from a function that returns a multidimensional ***pointer?
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;
}
I think you need something like
Normal* 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.
Normal 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).
Normal* 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).
bool 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)
optional<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 ...
}
}
Source: https://cs50.harvard.edu/x/2023/labs/5/
Here is the portion that I need help with:
// Create a new individual with `generations`
person *create_family(int generations)
{
// TODO: Allocate memory for new person
person *new_person = malloc(sizeof(person));
if (new_person == NULL)
{
return 1;
}Here is what ChatGPT says on my return 1 usage:
The TODO comment indicates that you need to allocate memory for a new person structure. In the provided code, you're using malloc(sizeof(person))to allocate memory dynamically. However, when memory allocation fails (i.e., malloc returns NULL), you're returning the integer 1 from the create_family function. Typically, a function returning a pointer should return NULL to indicate a failure.
Next, I rephrased the code:
// Create a new individual with `generations`
person *create_family(int generations)
{
// TODO: Allocate memory for new person
person *new_person = malloc(sizeof(person));
if (!new_person)
{
return 1;
}ChatGPT reply:
Your updated code checks if new_person is NULL using the condition if (!new_person).
However, it's better to return NULL*(a pointer) in case of memory allocation failure, rather than the integer* 1.
Here's the modified code:
// Create a new individual with `generations`
person *create_family(int generations)
{
// TODO: Allocate memory for new person
person *new_person = malloc(sizeof(person));
// Check if memory allocation was successful
if (!new_person)
{
fprintf(stderr, "Memory allocation failed.\n");
return NULL;
}
// Rest of the code for creating the family tree
// ...
return new_person;
}In this modification:
-
If memory allocation fails, the function prints an error message to the standard error stream using fprintf(stderr, "Memory allocation failed.\n");
-
return NULL;
is used to indicate that the function failed to create a new person due to a memory allocation failure. -
If memory allocation is successful, the function proceeds with the rest of the code for creating the family tree.
Returning NULL in case of memory allocation failure is a common practice in C, as it allows the calling code to check for errors by examining the returned pointer.
Full project code provided by CS50:
// Simulate genetic inheritance of blood type
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// Each person has two parents and two alleles
typedef struct person
{
struct person *parents[2];
char alleles[2];
} person;
const int GENERATIONS = 3;
const int INDENT_LENGTH = 4;
person *create_family(int generations);
void print_family(person *p, int generation);
void free_family(person *p);
char random_allele();
int main(void)
{
// Seed random number generator
srand(time(0));
// Create a new family with three generations
person *p = create_family(GENERATIONS);
// Print family tree of blood types
print_family(p, 0);
// Free memory
free_family(p);
}
// Create a new individual with `generations`
person *create_family(int generations)
{
// TODO: Allocate memory for new person
person *new_person = malloc(sizeof(person));
if (new_person == NULL)
{
return 1;
}
// If there are still generations left to create
if (generations > 1)
{
// Create two new parents for current person by recursively calling create_family
person *parent0 = create_family(generations - 1);
person *parent1 = create_family(generations - 1);
// TODO: Set parent pointers for current person
// TODO: Randomly assign current person's alleles based on the alleles of their parents
}
// If there are no generations left to create
else
{
// TODO: Set parent pointers to NULL
// TODO: Randomly assign alleles
}
// TODO: Return newly created person
return NULL;
}
// Free `p` and all ancestors of `p`.
void free_family(person *p)
{
// TODO: Handle base case
// TODO: Free parents recursively
// TODO: Free child
}
// Print each family member and their alleles.
void print_family(person *p, int generation)
{
// Handle base case
if (p == NULL)
{
return;
}
// Print indentation
for (int i = 0; i < generation * INDENT_LENGTH; i++)
{
printf(" ");
}
// Print person
if (generation == 0)
{
printf("Child (Generation %i): blood type %c%c\n", generation, p->alleles[0], p->alleles[1]);
}
else if (generation == 1)
{
printf("Parent (Generation %i): blood type %c%c\n", generation, p->alleles[0], p->alleles[1]);
}
else
{
for (int i = 0; i < generation - 2; i++)
{
printf("Great-");
}
printf("Grandparent (Generation %i): blood type %c%c\n", generation, p->alleles[0], p->alleles[1]);
}
// Print parents of current generation
print_family(p->parents[0], generation + 1);
print_family(p->parents[1], generation + 1);
}
// Randomly chooses a blood type allele.
char random_allele()
{
int r = rand() % 3;
if (r == 0)
{
return 'A';
}
else if (r == 1)
{
return 'B';
}
else
{
return 'O';
}
}
Maybe there are some basic things you should rethink:
First, only pointers can be NULL, but not objects. Hence, if you return an object of type struct Stack (which is not a pointer), you cannot return NULL but just an instance of struct Stack.
Second, passing in and returning an object of struct Stack by value will result in copying the respective object; I think that passing references or pointers would be a better choice; and - if you pass in and return a pointer, you could also return NULL to indicate a full stack or some other issue.
The problem is that your function must return a value that has the type Stack.
The code you provided doesn't define the type of NULL, but, since you're not seeing another error and you're assigning it to node, I would guess that the type of NULL is StackNode *... or, at least, something compatible with that.
So, there's your problem. You're trying to return something with the type StackNode * when your function claims to return a Stack.
Your best bet is to redesign this function that returns the result of the push operation and not the Stack itself.
I am very sure that someone told me once that NULL is defined as a pointer to void. I leafed through the K&R, and NULL was just said to be interchangeable with zero.
But either way, if I have a function that returns a 3d char array (array of arrays of strings), can I then return NULL if something goes wrong? will it be a valid return type?
Many functions that return pointers return NULL if something goes wrong - fopen for instance where you check for NULL and then perror.
But I am confused about multi-dimensional pointers.
I mean, I know that they are technically just pointers. I am unsure what the multiple asterisks do except tell the programmer how many dimensions there are. Hmmm Is this the solution?
Comments?
In C++, references can't be null. If you want to optionally return null if nothing is found, you need to return a pointer, not a reference:
Attr *getAttribute(const string& attribute_name) const {
//search collection
//if found at i
return &attributes[i];
//if not found
return nullptr;
}
Otherwise, if you insist on returning by reference, then you should throw an exception if the attribute isn't found.
(By the way, I'm a little worried about your method being const and returning a non-const attribute. For philosophical reasons, I'd suggest returning const Attr *. If you also may want to modify this attribute, you can overload with a non-const method returning a non-const attribute as well.)
There are several possible answers here. You want to return something that might exist. Here are some options, ranging from my least preferred to most preferred:
Return by reference, and signal can-not-find by exception.
Attr& getAttribute(const string& attribute_name) const { //search collection //if found at i return attributes[i]; //if not found throw no_such_attribute_error; }
It's likely that not finding attributes is a normal part of execution, and hence not very exceptional. The handling for this would be noisy. A null value cannot be returned because it's undefined behaviour to have null references.
Return by pointer
Attr* getAttribute(const string& attribute_name) const { //search collection //if found at i return &attributes[i]; //if not found return nullptr; }
It's easy to forget to check whether a result from getAttribute would be a non-NULL pointer, and is an easy source of bugs.
Use Boost.Optional
boost::optional<Attr&> getAttribute(const string& attribute_name) const { //search collection //if found at i return attributes[i]; //if not found return boost::optional<Attr&>(); }
A boost::optional signifies exactly what is going on here, and has easy methods for inspecting whether such an attribute was found.
Side note: std::optional was recently voted into C++17, so this will be a "standard" thing in the near future.
Returning NULL in case of success (the most simple case for success at that) is definitely contrary to what most people will expect.
Returning a pointer that the user has to manually destruct isn’t super great either. I’d suggest using C++11 unique_ptr but using C++11 may not be feasible in your case.
One thought I had is to make TestRoute private and have the Planner call it whenever it computes a new route.
If the test fails, return NULL, otherwise return the route.
What’s nice about this approach is that you can implement TestRoute however you (or your colleague) please, and the user of the class won’t need to know the details of how it is implemented. The user will just ask for a route from point A to point B and will be guaranteed it’s a valid route with refueling points so long as they don’t receive NULL.
You could also split your method into a few different methods if the performance hit isn’t too great.
For example, for TestRoute, have it return true if the route is possible, false if not.
bool TestRoute(const Route* r)
Have another method TestRouteNeedRefuel that returns true if the route will require refueling, false if not
bool TestRouteNeedRefuel(const Route* r)
Then have a final method, GenerateRefuelRoute that returns a new route with the proper refuel points
Route* TestRoute(const Route* r)
//use this if at all possible
std::unique_ptr<Route> TestRoute(const Route* r)
As far as performance goes, remember to profile before making assumptions. If your colleague is worried about copying Route more than needed (and he may have good reason to, as we don't know how expensive it is or what the target platform is) then clearly performance is an important requirement. I would suggest first implementing as clean an interface as can be done, profiling to find where the bottlenecks REALLY are, and then implementing a few speed hacks where necessary.
I would generally consider returning a pointer from a method in C++ a bad design, and mixing error states and payload data in the return value, too; this is a recipe for unmaintainable code.
Suggested change: Return the fail/success status as int value (or use ternary logic, e. g. boost::tribool), and pass the argument as non-const reference:
/** @returns
- 1 if a solution has been found. The argument will be updated.
- 0 if the request has been processed sucessfully,
but no (immediate) solution has been found.
The argument is not modified in this case.
- -1 if the request failed. The argument is not modified. */
int findSolution(MyClass& argument);
Usage example, leaving out premature optimization to avoid "unnecessary" copies:
MyClass objectToTest(originalUnmutableObject);
switch(findSolution(objectToTest))
{
case 1:
//Replace original with updated object, or whatever
break;
case 0:
//Nothing to do (?)
break;
case -1:
//Error handling
break;
default:
//Unexpected return value
assert(false);
}
An alternative, more sophisticated and reusable approach could be to bundle error state and object into a generic result class; this pattern was inspired by Rust. I leave the implementation of Result to you.
template<typename T>
class Result
{
public:
Result() = delete;
Result(int error);
Result(const T& data);
Result(T&& data);
//Methods
bool isOk() const;
bool isError(int error) const;
int error() const;
const T& data() const;
private:
//Variables
int m_error = 0;
T m_data;
};
...
Result<MyClass> findSolution(const MyClass& argument)
{
int errorCode = 0;
...
if(errorCode != 0)
return Result(errorCode);
else if(solutionFound)
//Error code of result will be 0, Result::isOk() == true
return Result(update(argument, solution));
else
//Error code of result will be 1, Result::isOk() == false
return Result(1);
}
While freeing memory, this is how I proceeded:
// Free `p` and all ancestors of `p`.
void free_family(person *p)
{
// TODO: Handle base case
if (p == NULL)
{
return NULL;
}It appears (ChatGPT) that the following will be the correct way:
// Free `p` and all ancestors of `p`.
void free_family(person *p)
{
// Handle base case
if (p == NULL)
{
return;
}In the context of freeing memory, you typically don't return anything (NULLor otherwise) because you are modifying memory, not producing a result (ChatGPT).
The distinction seems subtle and somewhat vague though makes sense.
Source: https://learning.edx.org/course/course-v1:HarvardX+CS50+X/home
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 cannot do this during references, as they should never be NULL. There are basically three options, one using a pointer, the others using value semantics.
With a pointer (note: this requires that the resource doesn't get destructed while the caller has a pointer to it; also make sure the caller knows it doesn't need to delete the object):
SomeResource* SomeClass::getSomething(std::string name) { std::map<std::string, SomeResource>::iterator it = content_.find(name); if (it != content_.end()) return &(*it); return NULL; }Using
std::pairwith aboolto indicate if the item is valid or not (note: requires that SomeResource has an appropriate default constructor and is not expensive to construct):std::pair<SomeResource, bool> SomeClass::getSomething(std::string name) { std::map<std::string, SomeResource>::iterator it = content_.find(name); if (it != content_.end()) return std::make_pair(*it, true); return std::make_pair(SomeResource(), false); }Using
boost::optional:boost::optional<SomeResource> SomeClass::getSomething(std::string name) { std::map<std::string, SomeResource>::iterator it = content_.find(name); if (it != content_.end()) return *it; return boost::optional<SomeResource>(); }
If you want value semantics and have the ability to use Boost, I'd recommend option three. The primary advantage of boost::optional over std::pair is that an unitialized boost::optional value doesn't construct the type its encapsulating. This means it works for types that have no default constructor and saves time/memory for types with a non-trivial default constructor.
I also modified your example so you're not searching the map twice (by reusing the iterator).
Why "besides using pointers"? Using pointers is the way you do it in C++. Unless you define some "optional" type which has something like the isNull() function you mentioned. (or use an existing one, like boost::optional)
References are designed, and guaranteed, to never be null. Asking "so how do I make them null" is nonsensical. You use pointers when you need a "nullable reference".