Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointers and enum in C [closed]

Tags:

c++

c

enums

I'm trying to rewrite my C++ code to C and got problems with comparising enum by pointers. Please take a look.

Enum:

enum state{TITLE,PLAY,LOST}

My function looks like that:

void ChangeState(int *state, int NewState)
{
state = NewState;

if (state == TITLE)
{
/* something */
}
else if (state == PLAY)
{
/* something2 */
}
else if (state == LOST)
{
/* something3 */
}

}

And when I try calling this function by:

ChangeState(&state, TITLE)

etc. it doesn't work correctly. Also when I put in my code:

if (state == TITLE)
{
/* instructions */ 
}

What is my mistake? Thanks from advance for your time.

like image 726
nikodamn Avatar asked May 09 '26 00:05

nikodamn


2 Answers

You need to dereference the pointer (use *state) to read the value it points to

This means your code should change to

void ChangeState(int *state, int NewState)
{
    *state = NewState;

    if (*state == TITLE)
    {
        /* something */
    }
    else if (*state == PLAY)
    {
        /* something2 */
    }
    else if (*state == LOST)
    {
        /* something3 */
    }

}
like image 83
simonc Avatar answered May 10 '26 12:05

simonc


In addition to simonc answer, you can also change the if statements by a switch. Given the case (working with enums) is more appropiated.

void ChangeState(int *state, int NewState)
{
    *state = NewState;

    switch (*state)
    {
        case TITLE: 
            // ...
            break;
        case PLAY:
            // ...  
            break;
        case LOST:
            // ...  
            break;
        default: break;
    }
}
like image 29
Raydel Miranda Avatar answered May 10 '26 12:05

Raydel Miranda



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!