why does this if-function without else does not work

(Code was written in Visual Studio Express)
The following function is called multiple times in a while loop. If m_nWaitToInitCounter, which is set to an int(e.g.: 100) at the beginning of the program, gets zero an a chKeyAdd is 32, which is read in from keyboard, an character is added to an array. If it´s not zero it´s value is decremented by one. I checked if chKeyAdd realy is 32 and even set it 32 by default, but the function only works when I add the else before the m_nW..--. Just closing the if block with } does not work. Why?

1
2
3
4
5
6
7
8
9
10
11
12
13
void Character::addcharacterifallowed(int nXPos, int nYPos, char chKeyAdd, bool bPrintOption)
{
	if(m_nWaitToInitCounter==0)
	{
		if(chKeyAdd==32)
		{
			ArrayOfCharacters.addcharacter(nXPos, nYPos, bPrintOption, m_nWaitToMoveStd); //adds a character to an array
			m_nWaitToInitCounter=m_nWaitToInitStd;
		}
	}
	else //just leaving this else away will cause the function to work wrong
		m_nWaitToInitCounter--;
}
Is the m_nWaitToInitCounter variable decrimented/updated somewhere else in the code?
no, it is only decremented there.
it is really strange to me, because I used cout to controll if all the values are like I thought, and they were. I had no idea why the program was not working fine, then I entered else just for fun and suddenly it worked.
Without the `else' you will be always executing the decrement.
If the user did not input 32 (¿space?), then counter would be negative.
If the user did input 32, then counter would be one less than what it is supposed to be.

¿what is the purpose of the program?


> the function to work wrong
not a good description
Last edited on
Topic archived. No new replies allowed.