1

I am in the process of changing my C++ code into C code because I find myself gravitating toward more purely functional programs and am not really using any of the C++ features. The speedy compiling is also a plus.

I am having trouble with this particular bit in my header:

void gameLoop();
void doStuff();

enum GameState
{
    MENU, PLAY, EXIT
};

GameState gameState;

which I want to use for functions like this in my source:

void gameLoop() 
{
    while (gameState != GameState::EXIT)
    {
        doStuff();

    }
}
4
  • In C and you cannot use ::; you need to use while (gameState != EXIT) (this should also work in C++ and that's why in C++ you should use enum class. Commented Jun 18, 2021 at 16:44
  • 1
    Please don't modify your question in a way that makes answers nonsensical. You removed the GameState::EXIT from the question and now your switch statement is malformed. Commented Jun 18, 2021 at 17:30
  • Sorry about that. Fixed to show both the original and modified code in unambiguous way Commented Jun 18, 2021 at 17:41
  • If you want more purely functional programming, C++ is to me a far better choice than C because it has lambda functions, implementing closures. Having true closures in pure C seems to be difficult and very verbose. Commented Jun 19, 2021 at 6:53

1 Answer 1

4

As pointed out in the comments, you can't use the scope-resolution operator (::) in C (there is no such operator). Further, if you want to use GameState as a variable type (as in your declaration, GameState gameState;) then you will need to explicitly define it as a type, using the typedef keyword.

Here's a version of the code you posted translated to C (note also the explicit void argument list declarations):

void gameLoop(void);
void doStuff(void);

typedef enum {
    MENU, PLAY, EXIT
} GameState;

GameState gameState;

void gameLoop(void)
{
    while (gameState != EXIT) {
        doStuff();
    }
}

As an improvement, you may like to add suitable 'prefixes' to the enum values, to avoid possible clashes with similar IDs declared elsewhere:

typedef enum {
    gsMENU, gsPLAY, gsEXIT
} GameState;
Sign up to request clarification or add additional context in comments.

1 Comment

enum GameState {...} gameState; saves having to pollute the typedef namespace, which gets pretty crowded. See namespaces in C.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.