How to run main statement and else statement only once, inside loop? - c++

So I'm trying to add controller support to an old game, but am having some trouble with the logic. I need to execute a command once a trigger is pressed, one time. Otherwise I need to execute a command one time if the trigger is released. All inside a while loop, I know I'm missing something obvious. I'm having trouble only sending the -attack command once.
while (true) {
Sleep(100);
bool flag = false;
if ((gamepad.rightTrigger == 1) && (flag == false))
{
SendCommandToConsole(0, 0, "+attack");
flag = true;
}
else if ((gamepad.rightTrigger == 0) && (flag == true))
{
SendCommandToConsole(0, 0, "-attack");
}
}

Let me show you my proposal:
bool flag = false;
while (true) {
Sleep(100);
if ((gamepad.rightTrigger == 1) && (!flag))
{
SendCommandToConsole(0, 0, "+attack");
flag = true;
}
else if ((gamepad.rightTrigger == 0) && flag)
{
SendCommandToConsole(0, 0, "-attack");
}
}
You see three things:
flag is declared outside of the while-loop, which has been proposed before and which is the answer to your question.
Don't check for flag == true or flag == false, just for flag or !flag, this improves the readability of your code.
I removed some obsolete empty lines. It's ok to leave an empty line between different parts of your source code, but it's advised to keep if-, then-, else-loops together, also for readability purposes.

Related

why are my if and else if statements not running?

same as title.
const inputs =document.querySelectorAll('input');
inputs.forEach(function(_inputs){
_inputs.readOnly = !_inputs.readOnly;
if(_inputs.readyOnly == false){
_inputs.classList.remove("readOnlyItem")
_inputs.classList.add("notReadOnly")
}else if(_inputs.readyOnly == true){
_inputs.classList.add("readOnlyItem")
_inputs.classList.remove("notReadOnly")
}
});
As far as I can tell every thing seems right and should be working but the if statments never return true for some reason.

return does not stop function, Recursive function issue? (programming exercise, Dynamic Programming, Levenshtein Back-trace)

the printOptimalAlignment function is misbehaving. goto and return will not exit when the function reaches location (1,1)... where it should end, no crash and it stops at seemingly an arbitrary location of (6,6)... because for some reason it increments at the end of the function even though there is no increment-er for the values int yL, int xL, (but I don't follow why it calls itself if it gets to the end of the function without any "hits" on the if statements.
Full code:
https://repl.it/#fulloutfool/Edit-Distance
void printOptimalAlignment(int** arr, string y, string x,int yL, int xL){
int I_weight=1, D_weight=1, R_weight=1;
bool printinfo_allot = 1,printinfo = 1;
if(printinfo_allot){
cout<<"Location: "<<"("<<xL<<","<<yL<<")"<<"-------------------------------\n";
cout<<"Same check Letters: "<<x[xL-2]<<","
<<y[yL-2]<<"("<<(x[xL-2] == y[yL-2])<<")"<<"\n";
cout<<"LL: "<<"("<<xL-1<<","<<yL<<")"
<<":"<<arr[yL][xL-1]
<<":"<<(arr[yL][xL-1]+I_weight)
<<":"<<(arr[yL][xL])
<<":"<<(((arr[yL][xL-1]+I_weight) == arr[yL][xL])==1)
<<":"<<(yL>=1 && xL>=1)<<"\n";
cout<<"xL state:"<<((&x[xL]))<<":"<<(x[xL-1])<<"\n";
cout<<"yL state:"<<((&y[yL]))<<":"<<(y[yL-1])<<"\n";
string tx = &x[xL];
cout<<x.length()<<","<<(tx.length()+1)<<"\n";
}
string tx = &x[xL]; // slopy hotfix
if(x.length()==(tx.length()+1)){
cout<<"return functionality not working?-=-=-=-=-=-=-=-=\n";
cout<<"-> Prep last, current distance = "<<arr[yL][xL] <<"\n";
return;
//printOptimalAlignment(arr,y,x,yL-1,xL-1);
//cant use this goto... but where does it go?
//goto because_Im_a_terrible_person;
throw "how?... breaking rules... make it stop";
}
if(yL>=1 && xL>=1 && (x[xL-2] == y[yL-2]) == 1){
if(printinfo){
cout<<"-> Same (same char), current distance = "<<arr[yL][xL] <<"\n";
}
printOptimalAlignment(arr,y,x,yL-1,xL-1);
}
if(yL>=1 && xL>=1 && (arr[yL-1][xL-1] == arr[yL][xL])){
if(printinfo){
cout<<"-> Swap (same int), current distance = "<<arr[yL][xL] <<"\n";
if(arr[yL-1][xL-1]==0)cout<<"---this is last---\n";
}
printOptimalAlignment(arr,y,x,yL-1,xL-1);
}
if(yL>0 && xL>0 && (arr[yL-1][xL]+D_weight == arr[yL][xL])){
if(printinfo){
cout<<"-> Delete, current distance = "<<arr[yL][xL]<<"\n";
}
printOptimalAlignment(arr,y,x,yL-1,xL);
}
//really weird ((yL>1 && xL>1) && (((arr[yL][xL-1]+I_weight) == arr[yL][xL])==1))
//not true if it is?
bool seperate = (((arr[yL][xL-1]+I_weight) == arr[yL][xL])==1);
if(yL>=1 && xL>=1){
if((((arr[yL][xL-1]+I_weight) == arr[yL][xL])==1) && (true)){
if(printinfo){
cout<<"-> Insert, current distance = "<<arr[yL][xL]<<"\n";
cout<<"Next Location1: "<<"("<<xL-1<<","<<yL<<")"<<"\n";
}
printOptimalAlignment(arr,y,x,yL,xL-1);
return;
//how does it get here... also return gets ignored... prob another stack issue
cout<<"insert function broke?????? # (1,1) ???????????????\n";
//return;
}
}
return;
cout<<"END... Hopefully.. if you see this Something went wrong\n";
because_Im_a_terrible_person:
cout<<"QUIT\n";
}
I suspect your problem is that your function calls itself and you don't appear to be taking into account what should happen next after that call to itself finishes. So you get to your finish condition where you say the return doesn't work, but it does... it just returns to where you left off in the previous call to printOptimalAlignment, which still might do something before returning to its caller, and so on. You have three different sites where you recursively call printOptimalAlignment that aren't immediately followed by a return statement, and at any of these it might be that the code will continue and trigger another of your conditional blocks.

Testing multiple boolean values in a single IF statement

I a newbie C++ programmer trying to test aruments/parameters passed to a program.
Multiple arguments can be passed to the program, however I want to test that if certain arguments are passed then other arguments become invalid.
e.g. PGM accepts arg(1) arg(2) arg(3) arg(4) arg(5) etc...
if arg(1) and arg(2) are supplied then arg(3), arg(4) and arg(5) etc... are invalid and the program should terminate with an error message if they are also supplied along with arg(1) and arg(2).
I've thought that using boolean IF tests would be a good way to check if certain values are true/false.
I searched on stackoverflow but not found an answer that encompasses exactly what i'm trying to do. If someone can point me in the right direction or suggest a far more efficient way of doing this I would be very grateful.
My code currently looks like this:
bool opt1 = false;
bool opt2 = false;
bool opt3 = false;
bool opt4 = false;
bool opt5 = false;
for(int i=1; i<argc; i++) {
char *str = argv[i];
if (strcmp (str, "-opt1:")==0) {opt1 = true;}
else if (strcmp (str, "-opt2:")==0) {opt2 = true;}
else if (strcmp (str, "-opt3:")==0) {opt3 = true;}
else if (strcmp (str, "-opt4:")==0) {opt4 = true;}
else if (strcmp (str, "-opt5:")==0) {opt5 = true;}
}
if((opt1) && (opt2) && (~(opt3)) && (~(opt4)) && (~(opt5)) {
** DO SOMETHING **
} else {
** DISPLAY ERROR MESSAGE AND USAGE TEXT **
}
A good solution would be using operands ! and &&
! denotes "not" (or in such case "not true") while && combines two different logical comparisons (in such case, "logic test 1" and "logic test 2")
Here's an example to do it:
if((opt1 && opt2)&&(!(opt3||opt4||opt5))){
/*
Do something if opt1 and opt2 are true and others are false
*/
}
This is practically the same as #Fareanor's solution above (first solution)
A possible fix could be (if I have well understood your problem):
if(opt1 && opt2) // opt3, opt4 and opt5 are invalid
{
if(!(opt3 || opt4 || opt5))
{
// Do something
}
else
{
// Display error message because at least opt3 or opt4 or opt5 is provided and not requested
}
}
else // opt3, opt4 and opt5 are valid
{
// Do something
}
But I think it could be better to just ignore the obsolete parameters instead of display an error while you can still run your process with only opt1 and opt2. Which could lead us to the simpler code:
if(opt1 && opt2)
{
// Do something without using opt3, opt4 and opt5
}
else
{
// Do something taking into account opt3, opt4 and opt5
}
I hope it is what you was looking for.

No return evaluation in nested if

After watching carefully the following code I can't see why the compiler is warning me with "warning: control reaches end of non-void function".
bool Foam::solidMagnetostaticModel::read()
{
if (regIOobject::read())
{
if (permeabilityModelPtr_->read(subDict("permeability")) && magnetizationModelPtr_->read(subDict("magnetization")))
{
return true;
}
}
else
{
return false;
}
}
I can't see where is the problem, the else statement should care for returning false in every case which the first if is not true.
Trace the code path when regIOobject::read() is true, but either of permeabilityModelPtr_->read(subDict("permeability")) or magnetizationModelPtr_->read(subDict("magnetization")) is false. In that case, you enter the top if block (excluding the possibility of entering its attached else block), but then fail to enter the nested if block:
bool Foam::solidMagnetostaticModel::read()
{
if (regIOobject::read())
{
// Cool, read() was true, now check next if...
if (permeabilityModelPtr_->read(subDict("permeability")) && magnetizationModelPtr_->read(subDict("magnetization")))
{
return true;
}
// Oh no, it was false, now we're here...
}
else
{
// First if was true, so we don't go here...
return false;
}
// End of function reached, where is the return???
}
The minimalist fix is to just remove the else { } wrapping, so any fallthrough ends up at return false;:
bool Foam::solidMagnetostaticModel::read()
{
if (regIOobject::read())
{
// Cool, read() was true, now check next if...
if (permeabilityModelPtr_->read(subDict("permeability")) && magnetizationModelPtr_->read(subDict("magnetization")))
{
return true;
}
// Oh no, it was false, now we're here...
}
// Oh, but we hit return false; so we're fine
return false;
}
Alternatively, avoid specifically mentioning true or false at all, since your function is logically just a result of anding three conditions together:
bool Foam::solidMagnetostaticModel::read()
{
// No need to use ifs or explicit references to true/false at all
return regIOobject::read() &&
permeabilityModelPtr_->read(subDict("permeability")) &&
magnetizationModelPtr_->read(subDict("magnetization"));
}
The nested if is the problem.
When that branch is not taken, there is no other paths to take
the else statement should care for returning false in every case which the first if is not true.
Correct, but what if the first if condition is true, but the second if condition is not?
That is: What if regIOobject::read() returns true, but permeabilityModelPtr_->read(subDict("permeability")) returns false?
Then the flow of control enters the first if block, does not return, but does not enter the else block (because the first condition was true), so it just falls off the end of the function without hitting a return statement.
If you want the else { return false; } part to apply to either condition, you could just naively copy/paste it:
if (COND1) {
if (COND2) {
return true;
} else {
return false;
}
} else {
return false;
}
But that's quite a bit of code duplication. A better solution is to replace the nested if by a single condition:
if (COND1 && COND2) {
return true;
} else {
return false;
}
There's still some duplication: Both branches consist of a return statement followed by some expression.
We can factor out the common parts (return) and push the condition into the expression:
return COND1 && COND2 ? true : false;
But ? true : false is redundant: If the condition is true, evaluate to true, else evaluate to false? Well, that's just what the condition itself does:
return COND1 && COND2;
Or with your concrete expressions:
return regIOobject::read()
&& permeabilityModelPtr_->read(subDict("permeability"))
&& magnetizationModelPtr_->read(subDict("magnetization"));

Optimize if else condition with (repeatable actions in branches)

I have this code. At first jobDone is false and the program does the first step, then the second and sets the jobDone variable to true stating that all tasks completed successfully.
But I might choose to run this bit of code again and I don't want to do the first step again since it might not be necessary. So if the job has been done at least once and if checkSomething() concludes that everything is OK it should go ahead and do only secondStep();
Otherwise, if checkSomething() finds out that something is wrong then I must repeat the first and as well the second step (like in the initial situation).
jobDone = false;
if (jobDone) {
if (checkSomething()) {
doSecondStep();
} else {
doFirstStep();
doSecondStep();
}
} else {
doFirstStep();
doSecondStep();
jobDone = true;
}
But I feel that i'm repeating myself. Is there a better way of writing this? Thank yoou.
if(jobDone && checkSomething()) {
doSecondStep();
} else {
doFirstStep();
doSecondStep();
jobDone = true;
}
The second step is always executed, I suggest you move that to the end first:
jobDone = false;
if (jobDone) {
if (!checkSomething()) {
doFirstStep();
}
} else {
doFirstStep();
jobDone = true;
}
doSecondStep();
However, there's only one condition that would cause doFirstStep() not to be executed and that's when jobDone == true and checkSomething == false, so we could just check for that.
The whole thing can be summarized to three lines:
if (!(jobDone && !checkSomething())) { doFirstStep(); }
jobDone = !jobDone;
doSecondStep();