My do while loop is only executing once [closed] - c++

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
I have made a sample code in c.
do
{
switch(i)
{
case 1:
{
cout<< "1\n";
break;
}
case 2:
{
cout<< "1\n";
break;
}
case 3:
{
continue;
}
}
}while (0);
Here in this code if value of i is 3 then i want to restart the do while loop which will result in an infinite loop. But unfortunately loop is not getting executed again. What will be the reason for that.?
I have checked the assembly code in visual studio of the same code and found that there is no JMP statement in the assembly for continue statement inside switch -case .

while (0) means it will fall out the bottom of the loop. Even if you have continue the condition is re-eval'd

When you do continue inside a do-while loop, it jumps at the evaluation at the bottom, that is always false in your case.

The other answers are explaining continue but it looks from your comments like you understand how that works.
if value of i is 3 then i want to restart the do while loop which will result in an infinite loop
The code is functioning as you describe - it is jumping to the 'while' condition on i==3. The only difference is that if you want an infinite loop you need while(1) not while(0).

Related

What is for(;;) loop in C++? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
My friend showed me this and I have no idea how it works and what it's called. Can someone explain to me how it loops the way it does? For example:
for(;;){
cout << "loop" << endl;
}
It will just keep looping the string forever. This kind of loop can be used for anything. How does this work?
According tho the language specification, empty condition in for iteration statament is equivalent to true condition.
6.5.3 The for statement
1 The for statement
for ( for-init-statement conditionopt; expressionopt) statement
is equivalent to
{
for-init-statement
while ( condition ) {
statement
expression ;
}
}
...
2 Either or both of the condition and the expression can be omitted. A missing condition makes the implied while clause equivalent to while(true).
So, the loop loops forever. That's all there is to it.
It loops infinitely as no initialization, conditional and increment values are passed in the parameters of the loop. A typical for loop takes parameters as follows: (<initialization>;<conditional>;<increment>)
This post explains it quite well in my opinion. See the answer by spex:
Why can the condition of a for-loop be left empty?
With the structure of the for loop being for(clause; expression-2; expression-3){}, when expression-2 is left out it is replaced with a nonzero constant. This is the part of the loop that determines whether it should keep looping or not. As a nonzero constant evaluates to true, it becomes an infinite loop.
That for loop essentially says the following three things (each separated by the semicolons in your for loop "header?"):
Don't initialize anything.
Don't break from the loop.
Perform no afterthoughts for each loop iteration.
Wikipedia's for loop page actually has a section about this.
As many have pointed out, it is equivalent to while (1).
When is it useful? Wherever you need an infinite loop such as:
A game loop - would be kinda useful to have the game, loop indefinitely until the user decides to quit the game.
OS scheduler - The scheduler needs to loop indefinitely, scheduling processes according to some algorithm until the OS stops
An intepreter - If you have ever programmed in python, you may have come across the interpreter which lets you type some command and then executes it. This is also implemented using a similar infinite loop
In all those examples, the common factor that leads to using an infinite loop is that the terminating condition is not known or the terminating condition is complex (game loops for example)

Error in Strings assignment. (C++) [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I've looked everywhere and I've found one for php but not c++. I'm making a little console rpg for a project in my into to c++ class and I'd like to avoid functions and/or if possible--but if not I'll use them.
Sample code:
int main(){
string pName;
string pWpnName;
int pDamage=0;
int wdSwrdD=1;
if (pDamage==wdSwrdD)pWpnName="Wooden Sword";
cout<<"Please enter a name";
cin>>pName;
pDamage++:
cout<<"Name: "<<pName<<endl;
cout<<"Weapon: "<<pWpnName<<endl;
return 0}
But whenever I do this it outputs: Name: pName (like it's supposed to) and Weapon:. It just stays blank and I have a feeling it's something to do with how I'm using strings...
You do not understand basics of how imperative languages (and C++ is one of them) work. Program executed statement by statement, and your if condition checks pDamage==wdSwrdD only once - when execution flow goes through that statement. So the fact that you increase pDamage later will not magically change pWpnName (and you need to change comparison operator == to assignment operator = in that if condition in addition to that, but I assume this is a typo).
So you most probably need a loop where execution flow is repeatedly goes through your if statement (that's what loops are created for), but it is difficult to say anything more based on information you provided.
You can use the getline() function:
cout<<"Please enter a name"<<endl;
getline(cin, pName);
pDamage++;
The function can get a line from a stream, set std::cin as the steam argument, and assign a line input to a variable.
Your problem is that you've made a typo: == is equality comparison, while = is assignment. So, your section of code should be changed:
if (pDamage==wdSwrdD)
pWpnName=="Wooden Sword"; // here you're doing comparison
...to:
if (pDamage==wdSwrdD)
pWpnName="Wooden Sword"; // here you're doing assignment
Most compilers should generate a warning for this behavior because it's an easy typo to make, but can be difficult to catch.
In your program you have not initialized the strings and your are taking user input for pName and therefore it displays the name . In case pWpnName it's not initialized while declaring and the "if condition never becomes true" because you have initialized pDamage=0 and wdSwrD=1 and as we know if(0==1) is never true the string pWpnName never gets initialized to Wooden Sword so it displays blank.

How should I break out from a loop? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
Whenever I need to break out from a for(unsigned int i=0;i<bound;++i) expression in C++, I simply set the index variable i=bound, the same way as described in this answer. I tend to avoid the break statement because, honestly, I have no good understanding of what it actually does.
Compare the two instructions:
for(unsigned int i=0;i<bound;++i) {
if (I need a break) {
break;
}
}
and
for(unsigned int i=0;i<bound;++i) {
if (I need a break) {
i=bound;
}
}
I speculate that the second method does one extra variable set and then one extra comparison between i and bound, so it looks more expensive, from performance point of view. The question is then is it cheaper to call break, then doing these two tests? Are the compiled binaries any different? Is there any instance, where the second method breaks, or can I safely choose either of these two alternatives?
Related: Does `break` work only for `for`, `while`, `do-while`, `switch' and for `if` statements?
Breaking out of a loop without a break statement [C]
Using break will be more future proof and more logical.
Consider the following example,
for (i = 0; i < NUM_OF_ELEMENTS; i++)
{
if(data[i] == expected_item)
break;
}
printf("\n Element %d is at index %d\n", expected_item, i);
But the second method won't be useful here.
There are three main technical differences that come to mind:
as other have stated, if your index variable is not confined to the for scope break leaves it intact, while your method destroys its content; when you are searching e.g. an array with break the code is more concise (you don't have to keep an extra variable to write down where you stopped);
break quits the loop immediately; your method requires you to execute the rest of the body. Of course you can always write:
for(int i=0; i<n; ++i) {
if(...) {
i=n;
} else {
rest of the loop body
}
}
but it adds visual and logical clutter to your loop;
break is almost surely going to be translated to a simple jmp to the instruction just following the loop (although, if you have block-scoped variables with a destructor the situation may be more complicated); your solution is not necessarily recognized by the compiler as equivalent.
You can actually see it here that gcc goes all the way to generate the code that moves n into i, while in the second case it jumps straight out of the loop.
On the stylistic side:
I find "your way" to be overly complicated and not idiomatic - if I encountered it in real code I would ask myself "why didn't he just use a break?", and then check twice to make sure that it's not like I'm missing some side effect and that the intent was actually just to jump out of the loop;
as other said, there's some risk of your inner assignment to go out of sync with the actual loop condition;
it doesn't scale when the loop condition becomes more complicated than a simple range check, both on the logic side (if the loop condition is complicated then tricking it can become more complicated) and on the performance side (if the loop condition is expensive and you already know you want to exit you don't want to check it again); this too can be circumvented by adding an extra variable (which is typically done in languages that lack break), but that's again extra distractions from what your algorithm is actually doing;
it doesn't work at all with range-based loops.
I prefer break; because it leaves the loop variable intact.
I frequently use this form while searching for something:
int i;
for(i=0; i<list.size(); ++i)
{
if (list[i] == target) // I found what I'm looking for!
{
break; // Stop searching by ending the loop.
}
}
if (i == list.size() ) // I still haven't found what I'm looking for -U2
{
// Not found.
}
else
{
// Do work with list[i].
}
Are the compiled binaries different?
Almost certainly yes. (although an optimizer may recognize your pattern, and reduce them to nearly the same)
The break; statement will likely be an assembly "jump" statement to jump to the next instruction outside the list, while leaving the control variable unchanged.
Assigning the variable (in non-optimized code) will result in an assignment to the control variable, a test of that variable, and then a resulting jump to end the loop.
As others have mentioned, assigning the variable to its final value is less future-proof, in case your loop condition changes in the future.
In general, when you say:
"I have no good understanding of what it actually does. (so I use a workaround)",
I respond with:
"Take the time to learn what it does! A main aspect of your job as a programmer is to learn stuff."
Using break to do this is idiomatic and should be the default, unless for some reason the rather obfuscatory alternative serves to set the stage for logic below. Even then I'd prefer to do the variable setup after the loop exits, moving that setting closer to its usage for clarity.
I cannot conceive of a scenario where the performance matters enough to worry about it. Maybe a more convoluted example would demonstrate that. As noted the answer for that is almost always 'measure, then tune'.
In adition to the break statement to exit a for or [do] while loop, the use of goto is permitted to break out nested loops, e.g.:
for (i=0; i<k; i++) {
for (j=0; j<l; j++) {
if (someCondition) {
goto end_i;
}
}
}
end_i:

Why is my if statement skipping the else? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I'm writing a small program that count the lines of code. Here is the definition of a line of code:
- any line that contains code necessary for the program to function.
- blank line is not a line of code.
- comment is not a line of code.
- if there's code and a comment right after on the same line, it counts as well.
So I have this piece of code (simple if statement):
found = lineRead.find("/*");
if(found != string::npos)
{
found = lineRead.find("*/");
if(found != string::npos)
inComment = false;
else
inComment == true;
}
return inComment;
Assume that
String lineRead = "cout<<\"helloworld!\";/*blockcomment"
Bool inComment (is true if the previous line didn't have end block comment token)
So my program reaches the first if statement because it found /* in that line, looks for */, goes to the second if statement then jumps straight to the return statement without changing inComment (which is supposed to be set to true because the text on the next line is still inside the block comment).
Anyone know why that is?
Your problem is the infamous "double equal sign."
inComment == true;
In C++, == is used for compare, NOT for assignment. I think what you want is:
inComment = true;
Double equal sign is for comparison not assignment. Probably just a typo as I assume you know that. But yea, change == to just = :-)

Is the code after 'break' executed? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
for (...)
for (...)
{
break;
break; // 1
}
Will the code at (1) execute? There could also be there continue or anything else. I know I could just check in my debugger but I wanna know what C++ standard says about it as my compiler might just be a special case.
As per the specifications
6.6.1 The break statement [stmt.break]
The break statement shall occur only in an iteration-statement or a switch statement and causes termination
of the smallest enclosing iteration-statement or switch statement; control passes to the statement
following the terminated statement, if any.
Hence 1 should not even reach . Some Java compiler might even flag that code unreachable.
As per standard
Within nested statements, the break statement ends the do, for, switch, or while statement that immediately encloses it.
So in your case it will always break at first and never come to second break statement.
The code at(1) will not be executed, break means jump out of the loop, so after the first break, the code will jump out of the inner loop.
Within that particular loop, no, no code after break will execute as break will drop out of that loop and continue execution from after the end of the inner for loop. Although any code outside of the inner loop that appears after the break (within the outer loop), will be executed.
No, each time the first break statement is hit the inner loop will exit and the second break statement will never be reached.
You can see here.
And I am sure the next break never exce . No matter what compiler you use.
No. The code execution jumps out of the inner first loop the moment a break is encountered.
Even if the code is this way
break;
continue;
break;
the same thing happens. Continue is just a way to tell the compiler to iterate the loop further skipping any code in between.