Go Down

Topic: how to return null instead of object? (Read 109 times) previous topic - next topic

_butch_

Jul 17, 2019, 10:41 pm Last Edit: Jul 18, 2019, 10:17 pm by _butch_
Hi,


I have an array of object RCStickAxis called myAxes..
I have a function which should return a single element of it, taking the id as argument.
I want to check for indexOutOfBounds. If I am out of bounds, I want to return null, otherwise I want to return the myAxis element.



I have following function in a class:

Code: [Select]
RCStickAxis RCStick::getAxis(unsigned char axis)
{
 // check bounds
 if (axis >=0 && axis < sizeof (myAxes))
 {
 // we are in bounds
 return myAxes[axis];
 }
 else
 {
 Log.fatal(F("RCStick::getAxis(unsigned char axis) requests stick which is out of bounds. Requested: %d, valid is 0 to %d. Returning NULL!\n"), axis, sizeof(myAxes)-1);
 return NULL;
 }
}



When trying to compile I get following error:

Code: [Select]
..\RCStick.cpp:33:10: error: could not convert '0' from 'int' to 'RCStickAxis'
 return NULL;
        ^
subdir.mk:34: recipe for target 'RCStick.cpp.o' failed
make: *** [RCStick.cpp.o] Error 1


What am I doing wrong or how do I implement it better? Try catch around the call from the outside?

Thanks, Andreas




Delta_G

returning null is what you do when you are dealing with pointers.  It doesn't really make sense here.  How would the caller test for it since it is looking for something of type RCStickAxis.

BTW:

Unless an RCStickaxis is the same size as a byte (which I highly doubt) then this:

Code: [Select]
if (axis >=0 && axis < sizeof (myAxes))
   {
      // we are in bounds
      return myAxes[axis];
   }


won't work.  You need:

Code: [Select]
if (axis >=0 && axis < (sizeof (myAxes)/sizeof(myAxes[0]))
   {
      // we are in bounds
      return myAxes[axis];
   }
|| | ||| | || | ||  ~Woodstock

Please do not PM with technical questions or comments.  Keep Arduino stuff out on the boards where it belongs.

septillion

If 'myAxes' is an array of 'RCStickAxis' object aka pointers you can use 'nullptr'.
Use fricking code tags!!!!
I want x => I would like x, I need help => I would like help, Need fast => Go and pay someone to do the job...

NEW Library to make fading leds a piece of cake
https://github.com/septillion-git/FadeLed

econjack

@_butch_: After 23 posts you should know how to use code tags when posting source code. If not, please read the first four posts at the top of this Forum.

Go Up