Note that in the screenshot, the ismoving
variable is updated after it is copied to wasmoving
, so it is perfectly possible that the value of ismoving
is different from the value of wasmoving
by the time the condition is evaluated.
sense of if - how is it possible that works
-
11-03-2022 - |
문제
I'm watching Mojam (live games programming, on HumbleBundle) and I saw this piece of code there
(here is screenshot of code)
I'm wondering how come the condition expression in last if statement (which is !wasmoving && ismoving
) ever evaluates to true (it does, programmer compiled it and animation was running).
I've tried this in my compiler
#include <iostream>
#include <cstdlib>
using namespace std;
int main(){
bool ismoving=5>0;
bool wasmoving=ismoving;
cout << "ismoving"<< ismoving << " oraz wasmoving " << wasmoving << endl;
if (!wasmoving && ismoving) cout << "1st = true 2nd = true" << endl;
system("PAUSE");
return 0;
}
and of course if the last if takes false path, nothing happens. Could anyone explain how it's posssible that code from screenshot worked?
해결책
다른 팁
Your transformation of the code from the screenshot is inaccurate. You have changed the order of the operations.
C++ and Java, like most mainstream programming languages, are "imperative" languages. This means that programs consist of sequences of instructions that are performed one after another. When that code does:
boolean wasJumping = isJumping;
isJumping = ...someCalculation...;
That first sets the value of wasJumping to be the current value of isJumping, then changes the value of isJumping to something else. wasJumping doesn't change - it still has the old value that was taken from isJumping.
If you come from a mathematical background this can be confusing. I find it helps to read "wasJumping = isJumping" as "wasJumping becomes equal to isJumping", not "wasJumping equals isJumping". The former reinforces that it's describes a change in a variable, rather than describing a permanent relationship between two values.