Nick Mundinger - 1 year ago 68
C++ Question

# Why is this function not returning the correct value?

I've made a function that converts an integer input into another integer, which it returns. Specifically, it takes in a console color, and returns a corresponding color which has the same background as the input, but with a white character.

This function always returns 255. What's going wrong?

``````int convertColorToPlayerColor(int color)
{
int playerColor = 0;

if (color <= 15)
playerColor = 15;

else if ((color > 15) && (color <= 31))
playerColor = 31;

else if ((color > 31) && (color <= 47))
playerColor = 47;

else if ((color > 47) && (color <= 63))
playerColor = 63;

else if ((color > 63) && (color <= 79))
playerColor = 79;

else if ((color > 79) && (color <= 95))
playerColor = 95;

else if ((color > 95) && (color <= 111))
playerColor = 111;

else if ((color > 111) && (color <= 127))
playerColor = 127;

else if ((color > 127) && (color <= 143))
playerColor = 159;

else if ((color > 159) && (color <= 175))
playerColor = 175;

else if ((color > 175) && (color <= 191))
playerColor = 191;

else if ((color > 191) && (color <= 207))
playerColor = 207;

else if ((color > 207) && (color <= 223))
playerColor = 223;

else if ((color > 223) && (color <= 239))
playerColor = 239;

else if (color > 239);
playerColor = 255;

return playerColor;
}
``````

You have an extra semicolon:

``````else if (color > 239);    // <--- the semicolon
``````

The extra semicolon gets parsed as the "then" part of an empty `if` statement. This effectively turns your function into

``````[ a long-winded if-else statement ]

playerColor = 255;

return playerColor;
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download