Please see the screenshot below. I noticed some erroneous results in my code so I went to debug.
As you can see, I put a break point when the variable 'latest' is equal to "5". BUT, apparently the application is hitting on this break point even thought 'latest' is equal to "2", not "5". Any idea what is going on here?
Format your code like this (>> denoting the breakpoint):
if (latest == "5")
{
>> ;
}
rather than this:
>> if (latest == "5") {;}
In the latter case the breakpoint is at the if, not at the ; inside the {}.
Cramming too many statements on the same line makes step by step debugging painful and makes the code less readable.
I put a break point when the variable latest is equal to "5"
No, you put a breakpoint where the variable latest is compared to "5". The comparison has to happen before the if statement knows which branch to take.
Your code rather than this:
if (latest == "5") {;}
Only use single-line if statements on a single line
The problem occurs when a single-line if the statement is broken up into two lines. While the compiler sees this as one statement guarded by a single condition, humans often accidentally read this is an if block, whether there are curly braces or not, thanks to the indentation. Humans notice the indentation, the compiler does not.
if (latest == "5")
;
If the statement you’re guarding is small, and not worth the extra heft of curly braces, just put it on the same line.
I am a novice programmer and was in lecture one evening, we were studying the "if,else" coding section from my professor and I was curious about an aspect of it. What I was curious about was if we have a bunch of nested if,else's in our program, is it just bad coding style to end an if,else with an "else,if" line of code instead of if "x", else "y"? For example,
if "x"
else if "y"
else if "z"
end
compared to
if "x"
else if "y"
else "z"
end
It would still run the program without an error, but are there consequences later on other than having bad programming style?
Behind the curtain JS dont really have else if, all it is doing is generating another if statement when parsed.
e.g:
if(foo){
} else if (baz){
}
becomes
if (foo){
} else {
if (baz){
}
}
So the reason for using another else if in the end instead of else is when you want to control the else statement as-well and not just pass to that case everything else that don't fit in your first condition... (In order to control the else condition and filter it to the necessary items only)
if you do have a really long statement with a lot of else-if conditions you should consider using switch statement instead.
It all depends on what you are looking to do. The former example makes sure that all IF requirements are met. There would be instances that none of the IFs get hit in this case.
In the latter example however, ELSE "Z" would get hit for sure if all above IFs fail. This would be useful if you are assigning a variable within your IFs - your variable will definitely have a value at the end of the IF statement. If it was as in the first example, the variable will be null and might result in a null error if you try to use it later.
If there are a lot of if-thens, I would checkout the case/switch statement as well, as it is more neater to implement.
Also, remember to comment your code well - especially explaining what all the nested IFs are doing.
Is there any guarantee, that the ifs of a if-else if-else if-else block, are tested in the order in which they have been written.
I am asking that because I am often trying to optimizing my code by putting the most frequent cases firsts and I want to know if some optimisations done by the compiler could change the order in which the if are tested.
So, if I am writting a code like that:
if (cond1) // First if (for the case I have the most often)
{
doSomething1();
}
else if (cond2) // Second if (for the second case I have the most often)
{
doSomething2();
}
else if (cond3) // Third if (for the third case I have the most often)
{
doSomething3();
}
else
{
doElse();
}
Is there any guarantee that after being compiled (for release), the first if will be tested, then the second if, then the third if (and finally the else is executed if none of the condition was true).
I know that when debugging, the ifs are executed in the order I wrote them, but will it stays true when the program is compiled for release (I am mostly using recent version of g++ and visual studio).
Also, since, the condition can have effect on the environnement (like if (i=a) or if(myfunction())), they should be executed as written, but I wonder if I am missing some optimisation that the compiler could do, that would change the order in which the ifs are tested. Especially, if the condition don't have side effects like that:
void test(int a)
{
if (a == 1)
{
doSomething1();
}
else if (a == 2)
{
doSomething1();
}
else if (a == 3)
{
doSomething1();
}
else
{
doSomething1();
}
}
Is there any guarantee that after being compiled (for release), the first if will be tested, then the second if, then the third if (and finally the else is executed if none of the condition was true).
Yes, but not specifically for if statements, for all of your (single threaded) code.
C++ code is executed top down, from the beginning to the end. The only time this may not be the case is when you make asynchronous calls or have multiple threads calling the same code simultaneously.
From C++03, § 6.4 Selection Statements:
1 selection-statement:
if ( condition ) statement
if ( condition ) statement else statement
switch ( condition ) statement
[...]
If the substatement in a selection-statement is a single statement and not a compound-statement, it is as if it was rewritten to be a compound-statement containing the original substatement. [Example:
if (x)
int i;
can be equivalently rewritten as
if (x) {
int i;
}
[...]
6.4.1 The if statement
1 If the condition (6.4) yields true the first substatement is executed. If the else part of the selection statement is present and the condition yields false, the second substatement is executed. [...]
From 6.4 1, your sample code is equivalent to:
if (cond1) {
doSomething1();
} else {
if (cond2) {
doSomething2();
} else {
if (cond3) {
doSomething3();
} else {
doElse();
}
}
}
Note this doesn't mean the code is transformed to the above, but rather that the two must behave the same.
From 6.4.1, an inner if statement is executed when the condition for the outer if is false. If the condition is true, the first branch is executed. While the standard doesn't explicitly state the second branch isn't executed when the condition is true, it's strongly implied by omission.
According to § 1.9 1:
The semantic descriptions in this International Standard define a parameterized nondeterministic abstract machine. This International Standard places no requirement on the structure of conforming implementations. In particular, they need not copy or emulate the structure of the abstract machine. Rather, conforming implementations are required to emulate (only) the observable behavior of the abstract machine as explained below.5)
5) This provision is sometimes called the “as-if” rule, because an implementation is free to disregard any requirement of this International Standard as long as the result is as if the requirement had been obeyed, as far as can be determined from the observable behavior of the program. For instance, an actual implementation need not evaluate part of an expression if it can deduce that its value is not used and that no side effects affecting the observable behavior of the program are produced.
So part of the else substatement may be executed if it's side-effect free and the results discarded even if the condition turns out to be true. A substatement condition, for example, may be partially executed within the processor pipeline if branch prediction incorrectly predicts that the condition will be false. However, the affects of this must not be noticeable, so (from your perspective) it's as if the substatements behave as outlined by §s 6.4 1 and 6.4.1 1.
No. The only thing that is guaranteed is that the observable behavior
be "as if" the ifs were evaluated in order. The evaluation of the
conditions may even be interleaved, with part of cond2 preceding cond1,
and another part after cond1 has been evaluated. On the other hand, the
guarantee that the results will be "as if" the ifs had been evaluated in
order, if some of the conditions have side effects, those side effects
won't occur if one of the earlier ifs was true.
With regards to optimization, by all means put the most likely
conditions first. In practice, the compiler will only move code if it
knows that the movement will improve things, so if the conditions are
more or less independent, and the compiler cannot "optimize" them by
folding parts of them, then the order will be preserved. Unless the
compiler is exceptionally good, and can determine that your ordering
wasn't optimal (on the basis of profiler output).
yes, the conditions are checked in the order of the if, else if, else structure.
Within a given conditional check, things can be tweaked a bit with parentheses.
C++ compilers are only allowed, with a few exceptions, to optimize statements to something so long as that something else behaves "as-if" it were performing the non-optimized statements.
Reordering the statements of an if/else tower would not behave "as-if" it had not been reordered (unless of course the compiler can prove that it would be, like when some checks are always true or false and have no side effects).
You absolutely can depend on the ordering of your if/else tower.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
When I was taking CS in college (mid 80's), one of the ideas that was constantly repeated was to always write loops which test at the top (while...) rather than at the bottom (do ... while) of the loop. These notions were often backed up with references to studies which showed that loops which tested at the top were statistically much more likely to be correct than their bottom-testing counterparts.
As a result, I almost always write loops which test at the top. I don't do it if it introduces extra complexity in the code, but that case seems rare. I notice that some programmers tend to almost exclusively write loops that test at the bottom. When I see constructs like:
if (condition)
{
do
{
...
} while (same condition);
}
or the inverse (if inside the while), it makes me wonder if they actually wrote it that way or if they added the if statement when they realized the loop didn't handle the null case.
I've done some googling, but haven't been able to find any literature on this subject. How do you guys (and gals) write your loops?
I always follow the rule that if it should run zero or more times, test at the beginning, if it must run once or more, test at the end. I do not see any logical reason to use the code you listed in your example. It only adds complexity.
Use while loops when you want to test a condition before the first iteration of the loop.
Use do-while loops when you want to test a condition after running the first iteration of the loop.
For example, if you find yourself doing something like either of these snippets:
func();
while (condition) {
func();
}
//or:
while (true){
func();
if (!condition) break;
}
You should rewrite it as:
do{
func();
} while(condition);
Difference is that the do loop executes "do something" once and then checks the condition to see if it should repeat the "do something" while the while loop checks the condition before doing anything
Does avoiding do/while really help make my code more readable?
No.
If it makes more sense to use a do/while loop, then do so. If you need to execute the body of a loop once before testing the condition, then a do/while loop is probably the most straightforward implementation.
First one may not execute at all if condition is false. Other one will execute at least once, then check the conidition.
For the sake of readability it seems sensible to test at the top. The fact it is a loop is important; the person reading the code should be aware of the loop conditions before trying to comprehend the body of the loop.
Here's a good real-world example I came across recently. Suppose you have a number of processing tasks (like processing elements in an array) and you wish to split the work between one thread per CPU core present. There must be at least one core to be running the current code! So you can use a do... while something like:
do {
get_tasks_for_core();
launch_thread();
} while (cores_remaining());
It's almost negligable, but it might be worth considering the performance benefit: it could equally be written as a standard while loop, but that would always make an unnecessary initial comparison that would always evaluate true - and on single-core, the do-while condition branches more predictably (always false, versus alternating true/false for a standard while).
Yaa..its true.. do while will run atleast one time.
Thats the only difference. Nothing else to debate on this
The first tests the condition before performing so it's possible your code won't ever enter the code underneath. The second will perform the code within before testing the condition.
The while loop will check "condition" first; if it's false, it will never "do something." But the do...while loop will "do something" first, then check "condition".
Yes, just like using for instead of while, or foreach instead of for improves readability. That said some circumstances need do while and I agree you would be silly to force those situations into a while loop.
It's more helpful to think in terms of common usage. The vast majority of while loops work quite naturally with while, even if they could be made to work with do...while, so basically you should use it when the difference doesn't matter. I would thus use do...while for the rare scenarios where it provides a noticeable improvement in readability.
The use cases are different for the two. This isn't a "best practices" question.
If you want a loop to execute based on the condition exclusively than use
for or while
If you want to do something once regardless of the the condition and then continue doing it based the condition evaluation.
do..while
For anyone who can't think of a reason to have a one-or-more times loop:
try {
someOperation();
} catch (Exception e) {
do {
if (e instanceof ExceptionIHandleInAWierdWay) {
HandleWierdException((ExceptionIHandleInAWierdWay)e);
}
} while ((e = e.getInnerException())!= null);
}
The same could be used for any sort of hierarchical structure.
in class Node:
public Node findSelfOrParentWithText(string text) {
Node node = this;
do {
if(node.containsText(text)) {
break;
}
} while((node = node.getParent()) != null);
return node;
}
A while() checks the condition before each execution of the loop body and a do...while() checks the condition after each execution of the loop body.
Thus, **do...while()**s will always execute the loop body at least once.
Functionally, a while() is equivalent to
startOfLoop:
if (!condition)
goto endOfLoop;
//loop body goes here
goto startOfLoop;
endOfLoop:
and a do...while() is equivalent to
startOfLoop:
//loop body
//goes here
if (condition)
goto startOfLoop;
Note that the implementation is probably more efficient than this. However, a do...while() does involve one less comparison than a while() so it is slightly faster. Use a do...while() if:
you know that the condition will always be true the first time around, or
you want the loop to execute once even if the condition is false to begin with.
Here is the translation:
do { y; } while(x);
Same as
{ y; } while(x) { y; }
Note the extra set of braces are for the case you have variable definitions in y. The scope of those must be kept local like in the do-loop case. So, a do-while loop just executes its body at least once. Apart from that, the two loops are identical. So if we apply this rule to your code
do {
// do something
} while (condition is true);
The corresponding while loop for your do-loop looks like
{
// do something
}
while (condition is true) {
// do something
}
Yes, you see the corresponding while for your do loop differs from your while :)
As noted by Piemasons, the difference is whether the loop executes once before doing the test, or if the test is done first so that the body of the loop might never execute.
The key question is which makes sense for your application.
To take two simple examples:
Say you're looping through the elements of an array. If the array has no elements, you don't want to process number one of zero. So you should use WHILE.
You want to display a message, accept a response, and if the response is invalid, ask again until you get a valid response. So you always want to ask once. You can't test if the response is valid until you get a response, so you have to go through the body of the loop once before you can test the condition. You should use DO/WHILE.
I tend to prefer do-while loops, myself. If the condition will always be true at the start of the loop, I prefer to test it at the end. To my eye, the whole point of testing conditions (other than assertions) is that one doesn't know the result of the test. If I see a while loop with the condition test at the top, my inclination is to consider the case that the loop executes zero times. If that can never happen, why not code in a way that clearly shows that?
It's actually meant for a different things. In C, you can use do - while construct to achieve both scenario (runs at least once and runs while true). But PASCAL has repeat - until and while for each scenario, and if I remember correctly, ADA has another construct that lets you quit in the middle, but of course that's not what you're asking.
My answer to your question : I like my loop with testing on top.
Both conventions are correct if you know how to write the code correctly :)
Usually the use of second convention ( do {} while() ) is meant to avoid have a duplicated statement outside the loop. Consider the following (over simplified) example:
a++;
while (a < n) {
a++;
}
can be written more concisely using
do {
a++;
} while (a < n)
Of course, this particular example can be written in an even more concise way as (assuming C syntax)
while (++a < n) {}
But I think you can see the point here.
while( someConditionMayBeFalse ){
// this will never run...
}
// then the alternative
do{
// this will run once even if the condition is false
while( someConditionMayBeFalse );
The difference is obvious and allows you to have code run and then evaluate the result to see if you have to "Do it again" and the other method of while allows you to have a block of script ignored if the conditional is not met.
I write mine pretty much exclusively testing at the top. It's less code, so for me at least, it's less potential to screw something up (e.g., copy-pasting the condition makes two places you always have to update it)
It really depends there are situations when you want to test at the top, others when you want to test at the bottom, and still others when you want to test in the middle.
However the example given seems absurd. If you are going to test at the top, don't use an if statement and test at the bottom, just use a while statement, that's what it is made for.
You should first think of the test as part of the loop code. If the test logically belongs at the start of the loop processing, then it's a top-of-the-loop test. If the test logically belongs at the end of the loop (i.e. it decides if the loop should continue to run), then it's probably a bottom-of-the-loop test.
You will have to do something fancy if the test logically belongs in them middle. :-)
I guess some people test at the bottom because you could save one or a few machine cycles by doing that 30 years ago.
To write code that is correct, one basically needs to perform a mental, perhaps informal proof of correctness.
To prove a loop correct, the standard way is to choose a loop invariant, and an induction proof. But skip the complicated words: what you do, informally, is figure out something that is true of each iteration of the loop, and that when the loop is done, what you wanted accomplished is now true. The loop invariant is false at the end, for the loop to terminate.
If the loop conditions map fairly easily to the invariant, and the invariant is at the top of the loop, and one infers that the invariant is true at the next iteration of the loop by working through the code of the loop, then it is easy to figure out that the loop is correct.
However, if the invariant is at the bottom of the loop, then unless you have an assertion just prior to the loop (a good practice) then it becomes more difficult because you have to essentially infer what that invariant should be, and that any code that ran before the loop makes the loop invariant true (since there is no loop precondition, code will execute in the loop). It just becomes that more difficult to prove correct, even if it is an informal in-your-head proof.
This isn't really an answer but a reiteration of something one of my lecturers said and it interested me at the time.
The two types of loop while..do and do..while are actually instances of a third more generic loop, which has the test somewhere in the middle.
begin loop
<Code block A>
loop condition
<Code block B>
end loop
Code block A is executed at least once and B is executed zero or more times, but isn't run on the very last (failing) iteration. a while loop is when code block a is empty and a do..while is when code block b is empty. But if you're writing a compiler, you might be interested in generalizing both cases to a loop like this.
In a typical Discrete Structures class in computer science, it's an easy proof that there is an equivalence mapping between the two.
Stylistically, I prefer while (easy-expr) { } when easy-expr is known up front and ready to go, and the loop doesn't have a lot of repeated overhead/initialization. I prefer do { } while (somewhat-less-easy-expr); when there is more repeated overhead and the condition may not be quite so simple to set up ahead of time. If I write an infinite loop, I always use while (true) { }. I can't explain why, but I just don't like writing for (;;) { }.
I would say it is bad practice to write if..do..while loops, for the simple reason that this increases the size of the code and causes code duplications. Code duplications are error prone and should be avoided, as any change to one part must be performed on the duplicate as well, which isn't always the case. Also, bigger code means a harder time on the cpu cache. Finally, it handles null cases, and solves head aches.
Only when the first loop is fundamentally different should one use do..while, say, if the code that makes you pass the loop condition (like initialization) is performed in the loop. Otherwise, if it certain that loop will never fall on the first iteration, then yes, a do..while is appropriate.
From my limited knowledge of code generation I think it may be a good idea to write bottom test loops since they enable the compiler to perform loop optimizations better. For bottom test loops it is guaranteed that the loop executes at least once. This means loop invariant code "dominates" the exit node. And thus can be safely moved just before the loop starts.