C++ How to make a non void function return nothing for if else statements?

Solution 1:

One way to handle this would be a std::optional<std::string>

#include <optional>

std::optional<std::string> dingas(std::string something)
{
    string letter;
    cout << "press a";
    cin >> letter;
    if (letter==something){
        return "a";
    }
    else
    {
        std::cout << "wrong letter";
        return std::nullopt;
    }
}

[1] https://en.cppreference.com/w/cpp/utility/optional

Solution 2:

If you want to read a single character you could use a char. However, if the function is declared to return a std::string but you do not want to return a std::string you have several options:

  • return an empty std::string
  • change signature to bool something(std::string& out) such that the return value signals sucess and when it is true the result is written to out.
  • change the return type to std::optional<std::string>. A std::optional<std::string> either contains a std::string or not.
  • throw an exception instead of return

Which one you pick is up to you. Exceptions should be used for exceptional cases, so you need to decide if not returning is "normal" or exceptional. It will require the caller to handle the exception. bool something(std::string&) is similarly inconvenient for the caller, because they need to check the return value and provide the string to be used. Usually a sentinal value (ie giving special meaning to the empty string) can cause problems, because one day you might confuse the sentinal with a proper return value. Though, as the function either returns a string with a single character or not, this isnt a big issue. I'd prefer the std::optional, but thats just my biased opinion.

Solution 3:

Consider using the exception mechanism for this: this carries the advantage that you can keep a reasonable return type, and you can also delegate handling of the exception to the caller of the function.

First, write

struct WrongLetterException : public std::exception{};

Then change the function to

std::string something (std::string something/*ToDo - is this correct?*/){
    std::string letter;
    std::cout << "press a";
    std::cin >> letter;
    if (letter == "a"/*note the change here*/){
        return a;
    }
    throw WrongLetterException();
}

In the caller to the function, you then catch (const WrongLetterException& ex) and deal with it as you see fit.