Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Return NULL instead of struct

I have a struct Foo. In pseudocode:

def FindFoo:
   foo = results of search
   foundFoo = true if a valid foo has been found  

   return foo if foundFoo else someErrorCode

How can I accomplish this in C++?

Edited to remove numerous inaccuracies.

like image 691
Nick Heiner Avatar asked Jun 15 '10 23:06

Nick Heiner


People also ask

Can we return null in C?

A function that returns pointer values can return a null pointer when it is unable to perform its task. (A null pointer used in this way is analogous to the EOF value that functions like getchar return.)

What does return null mean in C?

In computer programming, null is both a value and a pointer. Null is a built-in constant that has a value of zero. It is the same as the character 0 used to terminate strings in C. Null can also be the value of a pointer, which is the same as zero unless the CPU supports a special bit pattern for a null pointer.

Can you return null in an int function?

Int removes the fractional part of number and returns the resulting integer value. The data type of the return value is the same as that of the number parameter. If the numeric expression results in a null, Int returns a null.


1 Answers

C++ objects can never be null or empty. Pointers can hold a null pointer value indicating they point at nothing.

The typical solution would be to throw an exception. Otherwise, use a pointer; just make sure you aren't returning the address of a temporary.

I wouldn't recommend trying to teach yourself C++ with knowledge from other languages, you'll hurt yourself. Grab a good beginner-level book, it's the best way to learn.

like image 88
GManNickG Avatar answered Sep 20 '22 20:09

GManNickG