简体   繁体   中英

Is it bad to have functions return strings instead of ints? (C++)

I'm still relatively new to programming. I'm in the process of working on a game with SDL and I find myself wondering where or not I am using bad habits.

For example, I have a function called titleScreen(), where the user decides which mode of the game to enter.

I can either return a value from 0-3, then process it through an if/else/else/else statement to decide what mode they selected.

or

I can return a string such as "STORYMODE", "FREEPLAY", "TUTORIAL", or "QUIT" and use that to decide which mode.

I like the second mode because it eliminates the initital confusion on trying to figure out which mode was selected, but I have a feeling in the back of my head that there is a problem doing it that way.

In my situation, what is the best way to return a value?

In this case you should use enum listing all states to achieve readability without performance hit. For example:

enum  mode {
    STORYMODE,
    FREEPLAY,
    TUTORIAL,
    QUIT
}

You should use enums for that, that is actually int but just more readable. So I would create:

enum GameMode { STORYMODE, FREEPLAY, TUTORIAL, QUIT };

And have method return type GameMode.

EDIT 2:

If you have buttons for every game mode, just return enum or call some other method with enum parameter when button is clicked. Same way as you are doing now with string.

What about returning a shared pointer to a game object? Below is some pseudo code to get you started and whatever calls titleScreen should call operator() on the returned object.

class GameI {
public:
    virtual ~GameI() {};
    void operator() = 0;
}

typedef std::shared_ptr<GameI> SharedGame;

class GameStory {
public:
    void operator();
}

void GameStory::operator()
{
    ...
}

SharedGame titleScreen()
{
    ...
    return SharedGame(new GameStory());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM