C++ can an int function return something like "NULL"?

11,034

Solution 1

It really depends on the semantics of your function. If the function's contract is that it will return an int to the user and for some reason it is unable to do so, then your function should be throwing an exception. If the function's contract is that it will either return an int or nothing to the user, then you might want to use boost::optional.

Solution 2

NULL is of type void* and so it cannot just be passed to an int, but you can also just do something like:

#define NOT_FOUND -1

or just some number that you dont use.

Also, as @juanchopanza pointed out you can just throw an exception

Solution 3

Use Event-Driven Programming via: enums or #defines to set return codes:

(Warning this is a very naive example)

#define GOOD_INPUT 10001
#define BAD_INPUT 10002

int test_function() {
    std::string str;
    std::cout << "Enter a string:" << std::endl;
    std::cin >> str;

    if (!str.empty()) {
         return GOOD_INPUT;
    }
    else {
         return BAD_INPUT;
    }
}

Later on you can check to see if everything went well:

int rtn_code = test_function();

if (rtn_code == BAD_INPUT) {
    //something went wrong: say or do something.
}
Share:
11,034
maria
Author by

maria

Updated on June 04, 2022

Comments

  • maria
    maria almost 2 years

    I have a function that computes something and if the result is not valid i want to return something like "NULL". I have found a way using pointers, but is there an easier way to do that?