简体   繁体   中英

C++ Multiple Logical Operator

I'm rather new to C/C++. I have a segment of my application which doesn't seem to work as I'd want but I cannot understand why.

What I'm looking to do is when the 4 key is in the status of down, I'd like it to carry out the 'idle' function. I'd like the idle function to have 2 outcomes. If the Up OR Down OR Left OR Right OR LMouse AND RButton then carry out the 'movement rotation operation' code else just carry out the standard idle function. However within my code, it'll loop this while it's down but the moving() will only ever return 0

I've been messing with it for some time and trying to look on google for answers but I cannot understand why.

Here's my segment of code:

int moving()
{
    int u = GetAsyncKeyState(VK_UP);
    int d = GetAsyncKeyState(VK_DOWN);
    int l = GetAsyncKeyState(VK_LEFT);
    int r = GetAsyncKeyState(VK_RIGHT);
    int mr = GetAsyncKeyState(VK_RBUTTON);
    int ml = GetAsyncKeyState(VK_LBUTTON);
    if(u == 1 || d == 1 || l == 1 || r == 1 || mr == 1 && ml == 1)
    {
        return 1;
    }
}

void idle()
{
    cout << "moving = " << moving() << endl;
    if(moving() == 1)
    {
        cout << "Movement rotation operating." << endl;
    }
    else
    {
        cout << "This is the idle statement" << endl;
    }

}

int main()
{
    while(1)
    {
    if(GetAsyncKeyState('4'))
        {
            cout << "4 Pressed" << endl;
            idle();
        }
    }
}

Thank you in advance.

Your logic to determine the button combination needs an extra set of parentheses.

if(u == 1 || d == 1 || l == 1 || r == 1 || (mr == 1 && ml == 1))

Also, 1 will evaluate to true so you can say

if(u || d || l || r || (mr && ml))

You could also make the function return a bool since that is really what you're after.

bool moving()
{
    // ...
    // code for getting button states
    // ...
    return (u || d || l || r || (mr && ml))
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM