Function doesn't properly do my if statment

on line 76 starts my takeTurns function which is supposed to switch between the players after each while loop on line 32.

When I run it, the if statement the takeTurns functions isn't triggering properly. It only stays on one of the players and doesn't switch back and forth.

Would anyone have an idea why it would do this?

Thanks a lot

http://pastebin.com/xSdd6FW8
I think at that portion you are trying to toggle between players with the boolean.
If i got it correctly, you can do it like this

1
2
3
4
5
6
7
8
9
10
void takeTurns(bool winCheck, int player)
{
    if (!winCheck)
    {
         player=(player+1)%2;
    }
    move(player);
}

closed account (zb0S216C)
Your issue is the result of passing-by-value. Passing-by-value is a term which means the function argument is copied into a parameter. For example:

1
2
3
4
5
6
7
8
9
10
void function(int i_)
{
    // Work with "i_"...
}

int main()
{
    int a_(0);
    function(a_);
}

When function() is called, a_ is passed to it. The value of a_ is copied into i_, a parameter of function(). When i_ is manipulated, the changes will not affect a_.

To resolve this, you'll need to pass-by-reference. Passing-by-reference is another term that's similar to pass-by-value. The difference needs to be seen:

1
2
3
4
5
6
7
8
9
10
void function(int &i_)
{
    // Do something with "i_"...
}

int main()
{
    int a_(0);
    function(a_);
}

This code is almost exactly the same as the previous code. The only difference here is the use of the ampersand (&). In a declaration context, the ampersand is used to declare a reference. A reference is effectively another name for a variable/object. As a result, modifications to a reference will affect the variable/object is refers to (referent). In this case, when a_ is passed to function(), i_ will become another name for a_. Therefore, changes to i_ will affect a_.

Wazzak
Last edited on
Thank you Framework. That's what I suspected, but didn't know how to go about coding it. I thought as long as the var was global it would be fine, I completely forgot about pointers and references.

Thank you, that solved it.
Topic archived. No new replies allowed.