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.
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 */
}
}
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With