While loop execute twice in one function call - c++

I have a problem with the while loop, I have instructed that the key1 variable should only be executed when at least some "if" instructions have been executed, however, it re-executes the while loop even if the variable key1 is equal to 0.
It should be noted that I do not change the value of the key1 variable in another part of the function
void form_table(...) {
int key1=1;
while (key1 != 0) <==(2)
{
key1=0;
if (dx->get_numero() == 1 && dy->get_numero() == 1)
{
key1++;
//Some code
}
else if (dx->get_numero() == 1 && dy->get_numero() == 0)
{
key1++;
//some code
}
else if (dx->get_numero() == 0 && dy->get_numero() == 1)
{
key1++;
//some code
} <==(1)
else
break;//I put it in case, but even with that it goes back into the buble while
}
}//Here is the problem, when finish the funcion execution the program comes back to the line (1), and then re-runs the while cycle (2)

the loop works if key1 is different from 0 if you increment key1 and therefore it is different from 0 the cycle reinitiates.
you have to do:
while (key1 == 0) {
// rest of the code
}

Related

what is the use of if else statements?

I don't quite understand the meaning of else if statements.
why not just to continue with the if statements in case one is false?
it works the same.
example with if only that will work the same with else if:
function testSize(num) {
if (num < 5){
return "Tiny";
}
if (num < 10){
return "small";
}
return "Change Me";
}
testSize(7);
In your actual code you specify a return statement in the code associated to the if statement.
Suppose you don't specify a return statement or suppose today you specify a return statement but tomorrow you remove it to do a common return at the end of the method.
This code will test each condition even if the first one is true :
if (num < 5){
// do something
}
if (num < 10){
// do something
}
This code will not test the next condition if the first one is true :
if (num < 5){
// do something
}
else if (num < 10){
// do something
}
These two ways of doing have two distinct meanings.
When you have a series of if statements, you expect that more than one condition may be true.
When you have a series of if-else-if statements, you expect to have not more than one condition true.
Using the first form (a series of if) while functionally you expect to have not more than one condition true is misleading.
Besides, if the code is modified and you add a condition that is both true for two if statements while you don't want have this case, it would create an issue.
Your code is only showing your belief. What would happen in the example below?
function testSize(num) {
if (num < 5){
x = 1;
}
if (num < 10){
x = 2;
}
result = complex calculations;
}
function testSize2(num) {
if (num < 5){
x = 1;
} else if (num < 10){
x = 2;
}
return x * 2;
}
testSize(4); // result is 4
testSize2(4); // result is 2
x may also be involved in more calculations
if(condition) {...}
if(condition) {...}
if(condition) {...}
In above code, even if the first or second condition is true, third condition have to be checked.
if(condition) {}
else if(condition){}
else if(condition){}
Here if first condition is true, next two will not be checked. So, it saves time and is more readable logically.
A one way if statement takes an action if the specified condition is true.If the condition is false, nothing is done. But what if you want to take alternative actions when the conditions is false ? You can use a two-way if-else statement. The action that a two-way if-else statements specifies differ based on whether the condition is true or false.
Well, there is a bit different from this two statement.Consider the follow samples
if(a > 0) {
...
}
if( a == 0) {
...
}
if(a < 0) {
...
}
and
if(a > 0) {
...
}
else if( a == 0) {
...
}
else if(a < 0) {
...
}
when a is zero the last else if statement will not be execute while if need to compare third time.If a equals to 10, else if could be execute once while if is third.From this else if statement could be execute less and let your program a bit fast.
else if should be used when there are multiple conditions and you want only one of them to be executed, for instance:
if(num<3){ console.log('less than 3') }
else if(num<2){ console.log('less than 2')
If you use multiple if statements instead of using else if, it will be true for both the conditions if num = 1, and therefore it will print both the statements.
Multiple if statements are used when you want to run the code inside all those if statements whose conditions are true.
In your case it doesn't make a difference because the function will stop and return at the very first return statement it encounters. But let's say, the blocks' orders are interchanged, then your function will never return 'tiny' even if num = (anything less than 5).
I hope that helps!
If all your if branches terminate the function (e.g., but returning a value of throwing an exception), you're right, and you really don't need an else statement (although some coding standards might recommend it).
However, if the if branches don't terminate the function, you'd have to use an else or else if clause to prevent multiple blocks from being executed. Assume, e.g., you want to log a message to the console instead of returning it:
if (num < 5) {
console.log("Tiny");
} else if (num < 10) {
console.log("small");
} else {
console.log("Change Me");
}

Optimized code for two string compare in if condition

I want to do two string compare and used two different if condition. Is there any better way to do string compare in one if condition
if (strcmp(Buff1(), Config1) == 0)
{
if (strcmp(Buff2, Config2) == 0)
{
// my code goes here
}
}
The equivalent code is:
if ((strcmp(Buff1(), Config1) == 0)) &&
(strcmp(Buff2, Config2) == 0))
{
// my code goes here
}
Note: The compiler should generate the same machine code for both code samples. The difference is cosmetic and primarily aimed at the reader of the code.
You do get a difference when you add else clauses:
if (strcmp(Buff1(), Config1) == 0)
{
if (strcmp(Buff2, Config2) == 0)
{
// my code goes here
}
else
{
// else 1
}
}
else
{
// else 2
}
Compared to:
if ((strcmp(Buff1(), Config1) == 0)) &&
(strcmp(Buff2, Config2) == 0))
{
// my code goes here
}
else
{
// Single else clause
}
In addition to Klas's answer(just in case you're not familiar with the AND operator) - the AND operator ('&&') checks the first condition and it continues to check the second condition -only if- the first condition is true.
So in your specific question, it checks if the first couple of strings are equal and only if true (are equal), it checks if the second couple are also equal.
The obvious optimization (not mentioned yet), if you know anything about those strings, is to first perform the compare that is more likely to fail.

How to have if, else nested tree continue working through the remaining else if’s…

I have a mini program I’m working on for class. The program is of correct syntax. Logically I cannot get the program to compute the remaining data after it completes the first else if statement that it matches.
I am subtracting numbers from each (a >= b) at each else if, the remaining value I am then assigning to a variable temp and using (temp >= c), rinse and repeat till value is zero. Each else if, will assign a char ‘A’ – ‘Z’ depending on the scenario. The problem I am having is it will meet one of the first else if’s but will not continue working the remaining else-ifs. I know this is standard of how if, else works. My question is how would I go about getting the remaining else ifs examined after the first one checks out. Is the only solution to use a switch function? Is there no way I can use if else and have each else checked/passed till my value = 0?
Just forget using else if, use a chain of if statements instead. For example:
bool isThisThree(int number, string &message)
{
if(number == 1)
message = "No, it's a one!";
if(number == 2)
message = "No, it's a two!";
if(number == 3) {
message = "Yes!";
return true;
}
if(number == 4)
message = "No, it's a four!";
if(number == 5)
message = "No, it's a five!";
return false;
}
In this example, the if statements will be examined one by one until the function hits a return statement.

About increment operation in cpp

are following code samples equivalent?
This:
while (true)
if (!a[counter] || !b[counter++]) break;
and this:
while (true){
if (!a[counter] || !b[counter]) break;
counter++;
}
i mean, would increment be performed after all conditions' checking done?
Here:
int _strCmp(char* s1,char*s2)
{
int counter = 0;
while (s1[counter]==s2[counter])
if (!s1[counter] || !s2[counter++]) return 0;
if (s1[counter] > s2[counter])
return 1;
if (s1[counter] < s2[counter])
return-1;
return 0;
}
Are there some cases, when this function doesnt work correctly?
No they are not.
Here if !a[counter] returns true the OR'ed condition will not be evaluated.
The second condition in OR is only evaluated if the first condition is false. This is because anything OR'ed with true will be true.
Look at the following image :
As in the image you can see that case 2 is not equivalent
Since the it is incremented post-evaluation (rather than ++counter), the value that will be returned is the value before it is incremented. So, those are equivalent statements.
If counter = 6, then !b[counter++] will return b[6], and then increment 6 to 7.
You could try it yourself changing your code to this:
run = 5;
while (run > 0) {
run--;
if (!a[counterA] || !b[counterA++]) break;
}
run = 5;
while (run > 0){
run--;
if (!a[counterB] || !b[counterB]) break;
counter++;
}
// compare counterA and counterB
EDIT:
Regarding "i mean, would increment be performed after all conditions' checking done?"
No. There are post and preincrement operations. Since you are doing a postincrementation your value would be incremented after it's value was used to evaluate the expression.

I want to increment a counter by one in a while loop c++

I am trying to increment a lap counter in my game by one but because I have to put this code in the game loop my counter goes over every time by about 500 instead or moving up one. Here is my code. The checkpointPassed variable is only true when a checkpoint is passed through. I know this works and the checkpoint number is the current checkpoint and they start at 0.
if(checkpointNumber == 0 && checkpointPassed == true)
{
lapNumber += 1;
}
I can't post the game loop because it is quite large.
Any Help is appreciated.
EDIT
Here is some more of the code so you can see what I am trying to do.
if(distance > carRadius && markerCounter < 5000)
{
if(checkpointPassed == true)
{
markerCounter++;
}
}
if(checkpointNumber == 0 && checkpointPassed == true)
{
lapNumber += 1;
}
if(distance < carRadius)
{
markerCounter++;
cross->SetX(checkpointX);
cross->SetY(checkpointY);
cross->SetZ(checkpointZ);
checkpointNumber += 1;
checkpointPassed = true;
}
if(markerCounter > 4999)
{
checkpointPassed = false;
cross->SetPosition(0,-50,0);
markerCounter = 0;
}
Add another two variable called inCheckpoint, which stores whether the user is currently "inside" the checkpoint or not. This allows you to detect when the user enters a checkpoint and only increment the lapNumber then. The code would look as follows:
if(checkpointNumber == 0 && checkpointPassed == true)
{
if (inCheckpoint == false) /* previously not inside a checkpoint */
lapNumber += 1;
inCheckpoint = true;
}
else
{
inCheckpoint = false;
}
UPDATE: Don't rely on checkpointPassed:
if(distance < carRadius)
{
if (inCheckpoint == false) /* previously not inside a checkpoint */
lapNumber += 1;
inCheckpoint = true;
}
else
{
inCheckpoint = false;
}
You could set/pass a gueard value that indicates how many iterations in the game loop you are (or whether this is the first iteration). If it is the first iteration (within the current lap), increment the variable as you do now, otherwise don't
You will need to reset this guard value for each lap -- e.g. right after you increment lapNumber.
You might need to cancel the 'checkpointPassed` state.
if (checkpointNumber == 0 && checkpointPassed == true)
{
lapNumber += 1;
checkpointPassed = false;
}
This means that you won't be counting the lap again until the next time a checkpoint is passed, which is presumably when you need it counted.
However, if you need checkpointPassed true later in the loop, then you'll need to think whether you need yet another variable, such as lapCounted, which is set to false when checkpointPassed is set to true, and reset to true by the code above (instead of setting checkpointPassed, not as well as setting it).
If I understand correctly what you said, your 'if' statement is inside the main loop and when you pass a checkpoint, 'checkpointPassed' becomes true. For how long?
If it stays 'true' for a few iterations, then each time your game loop does an iteration,your lap counter is incremented. In this case, you should either set checkPointPassed to false at the end of the iteration, or use a different variable, that you set to true at the same time that checkPointPassed becomes true and false after incrementing.
If this does not answer your question, can you give a little more context as with only this part of the code, it is hard to figure out what you want to do.