What's the difference between these 2 'if' and 'if-else' statements? - if-statement

What is the difference between 2 if statements and 1 if-else statement?
int x;
cin >> x;
if (x==10)
cout << "Hello";
if (x!=10)
cout << "Hey";
int x;
cin >> x;
if (x==10)
cout << "Hello";
else
cout << "Hey";

In practice, the optimizer will probably make them exactly the same. The best thing to do in these cases is to try it - look at the assembly output of your compiler, and you'll see exactly what the difference is.

The difference is that in the second case the condition is checked and computed only once.

In the first example both are evaluated, always.
In the second example if first is true, it never gets to second.

The most important difference (to my mind) is that the first form is harder to read and is more error-prone.
The second form reads more like English: "If x is 10 then do this, else do that" whereas the first form essentially makes the two clauses unrelated. It's error prone because if you decide that the threshold 10 needs to change then you need to update it in two places rather than just one.
In terms of execution speed, I'd be very surprised if there is any difference at all. There will be two evaluations with the first form but that's the least of the problems. It's certainly not the sort of thing you should waste time optimising.

There is no visible output difference. However, it does make your code easier to read if you use the ladder one

if (x==10) //matches only if x is number 10 , then processor jump to next line i.e.
if (x!=10) // matches only if x is not number 10
where as
other if checked only , if the number is either 10 or anything else then 10.
In a way both will result same, but its just matter of statements.
so
in first example, both lines of if will be executed
in second example either of one is executed
So its better to use second one for performance

From a maintainability point of view the first one
violates the DRY principle.
is a lot harder to understand and modify. Not with a trivial condition, like here, but with a nice long condition you'll either have to just cut 'n paste the condition and slap a ! in front, or try to remember how De Morgan's laws were formulated... And some day that will fail, and the inverted if will fail to be the exact opposite of the first....
So, else is the way to go.

In the first block both if statement will run by the compiler...
But int the second one only 1 statement will run as both are linked with a single condition . Either if can be true or else can be true
You can understand this as considering 1st one as 'and' type
And the 2nd one as 'or' type

Related

basic if statement 3 values in c++

I am new and beginner in programming and dont quiet understand how to post my question here. Hope this works.
Anyways, im starting from basic and just learnt the "if" statement. But when i tried to create my own version its not working. My program below is showing all three cout results even if i enter only one option(attack or run or hide). It was working fine when there was just one "if" statement. I tried the "else if" too but then it only printed out the result "you have attacked" no matter what i chose. :( I used the search bar for similar questions that might have already been answered but didnt find much that could help me.
If there are similar questions then i'd appreciate if you could point me towards it, although i'd really be grateful if you could point out what my mistakes are specifically.
Thnx~
#include <iostream>
#include <string>
using namespace std;
int main(){
cout<<"Welcome to the jungle!!!"<<endl;
cout<<"--------"<<endl;
cout<<"Enemies approaches! \n Choose your next move! \n";
cout<<"Attack / Run / Hide \n\n\n";
string choice;
cin>>choice;
if(choice=="Attack"||"attack")
{
cout<<"You have attacked!"<<endl;
}
if(choice=="Run"||"run")
{
cout<<"You start running!"<<endl;
}
if(choice=="Hide"||"hide")
{
cout<<"You hide in a cave!"<<endl;
}
return 0;
}
if(choice=="Attack"||"attack")
does not mean "if choice contains "Attack", or choice contains "attack", do the thing".
It means "if choice contains "Attack", or "attack" is true, do the thing".
In pseudo-code, you expect:
if choice is the string "Attack"
or choice is the string "attack"
do a thing
but the or splits the statement into halves, and the second half doesn't mention the variable choice at all. It breaks down more like
if choice is the string "Attack"
or the string "attack" on its own is somehow true, whatever that might mean
do a thing
Since "attack" is a pointer to a char array, being true means it is not NULL, which is always the case, so this branch is always entered.
To express what you mean, write instead:
if(choice=="Attack"||choice=="attack")
Welcome to C/C++ world.
As you have already read in tutorials or book, the content inside the parens of an if has to be a boolean value. Now, a lot of stuff can be converted automatically to bool and as a condition for an if.
In particular, anything that can be converted to an int will, in turn, have a bool value attached to it. Pointers are of such kind.
If the value is different from 0 then the result will be -> true
0 otherwise.
Writing if(choice=="Attack"||"attack") you are telling the compiler to execute the content of the if either if the content of choice is equal to the string Attack or if the the pointer to the underlying const char* attack is not zero.
attack is a valid string which mean its value is not zero which in turn means you are getting a true out of it.
Same goes for all the others ifs. The second part of all you ifs are true cause they are not null pointers.
Change the all the ifs as the following: if(choice=="Attack"||choice=="attack") and the problem will be fixed.
You must use
if(choice=="Attack"||choice=="attack")
{
cout<<"You have attacked!"<<endl;
}
OR( || ) is a boolean operator.
So Anything other than 0 gives an impression of 1 in boolean. Thus the syntax in if code is always executed. This is the reason for in the else if case first statement is always executed (and further statements are skipped).
Also, using namespace std; is a bad practice since it makes our code confined to just one std library. instead you must use std:cout;

What errors are saved by brevity? [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 7 years ago.
Improve this question
"C++ Primer" (5th edition) suggests on page 149 that a brief code can be less error-prone than a longer alternative. It brings the following line of code to serve as an example:
cout << *iter++ << endl;
It claims that the above line is less error-prone than the alternative:
cout << *iter << endl;
++iter;
To me, even though the meaning of *iter++ is clear, this expression still requires a non-zero mental effort to parse and so the second version is more readable. So, I want to understand: what is more error-prone about the second version?
I also do not agree with the author.
Usually each code snippet has a tendency to be changed in the future.
For example this statement
cout << *iter++ << endl;
can be changed the following way
cout << *iter++ << ... << SomeFunction( *iter ) << endl;
In this case the code will have undefined behaviour because the order of evaluation of function arguments is unspecified.
So in my opinion this code snippet
cout << *iter << endl;
++iter;
is less error-prone.:)
Introducing side-effects in a code snippet does not make it less error-prone.
Moreover in the code snippet you showed there is no logical relation between the increment of the iterator and outputting its value.
cout << *iter++ << endl;
So it is unclear why the iterator is incremented in this statement.
Separating this statement into two statements makes the code snippet more clear because it seems that the incrementing is related to some other parts of the code.
The brevity makes the code more expressive. But it does not mean that it necessarily makes also the code less error-prone.:)
The thing is, when you have your function containing a few lines on code, each one of them is treated as a "step" to achieve some goal. When you read such a function you read each line and think what it does and why. In your example,
cout << *iter << endl;
++iter;
logically could be one step: "when iterating over the container, write each element to cout". It's because when you forget either of these lines, the whole step is incorrect. Of course, this very example is not particularly great, because it's not hard to come up with a code, in which the two lines are two different logic steps. However, I assume the author meant, that by writing
cout << *iter++ << endl;
you protect yourself from forgetting one part of a logic step as well as you make a signal for a reader that this is one logic step.
I can think about the lines being reordered for some reason (maybe they became separated by some other code and it was later modified), or an if/for/while being added, either without braces or with them wrongly placed:
++iter;
cout << *iter << endl;
if (some_condition)
cout << *iter << endl;
++iter;
while (something_happens)
{
cout << *iter << endl;
}
++iter;
In this small example, the bugs are quite obvious, but that may not be the case when you have a lot more lines.
(And yes, I know the indentation in the 2nd and 3rd examples should be corrected, but sadly I've seen lots of examples like these).
I couldn't disagree with the author more.
The expression *iter++ does two different things to iter - it dereferences it and increments it. Yes, the order is defined, but understanding the results of two actions on a single variable in a single expression requires inherently more brainpower than something which has only one effect on a single variable.
One of the most reliable ways to increase errors from a developer is to unnecessarily increase the brainpower needed to understand what their code actually does.
The virtue of breaking the effects into two distinct statements is that it is easier to understand.
The other phenomenon is that programmers who are taught to include two effects on a single variable in a single statement are more likely to craft expressions with even more effects on some poor variable. Apart from making their code even less comprehensible, it also increases the likelihood of undefined behaviour (since any expression that modifies any variable more than once in a single expression has undefined behaviour).
It might be worth comparing to similar constructs in other languages.
In python, to iterate over a sequence, we use a generator. There is essentially only one operation you can do with a generator: call next which obtains an element and advance the generator. Iteration, when done manually, is done by repeatedly calling next to get the terms of the sequence until it raises StopIteration to signal the end of the sequence.
In java, to iterate over a sequence, we us an Iterator. There is essentially only one operation you can do with an iterator: call next which obtains an element and advances the iterator. Iteration, when done manually, is done by repeatedly calling next to get the terms of the sequence until hasNext returns false to signal the end of the sequence.
In C/C++... we often want to get an element and advance through the sequence. It has been long established (AFAIK before C++ even existed) that this operation is *p++.
The only reason we are even contemplating the idea of breaking this into two steps -- one step being to get the current element and the other step being to advance to the next term -- is an artifact of an implementation detail.
In a situation where one is truly thinking of these two steps as being separate, independent things, then it would be best to keep them as separate expressions.
But it is relatively well established that that is not how people are thinking -- people are thinking in terms of "getting an element and advancing the iterator". Iteration, when done manually, is done by repeatedly invoking *iter++ to get the terms of the sequence, until iter == end_iter returns true to signify the end of the sequence.
When thinking this way, splitting the one conceptual step into two syntactically separate elements (*iter and ++iter) is more error prone than keeping it as a single step.
Not a good example, because you shouldn't use while without braces, but it could lead to errors like this: In this case you would have an infinite loop when adding the while.
while (*iter)
cout << *iter << endl;
++iter;
I think it is a bad example! Much better would be an example, where you have multiple dependent steps. Then someone copies some steps to another function, but misses some lines, which don't look they are semantically needed.

Read and write variable in an IF statement

I'm hoping to perform the following steps in a single IF statement to save on code writing:
If ret is TRUE, set ret to the result of function lookup(). If ret is now FALSE, print error message.
The code I've written to do this is as follows:
BOOLEAN ret = TRUE;
// ... functions assigning to `ret`
if ( ret && !(ret = lookup()) )
{
fprintf(stderr, "Error in lookup()\n");
}
I've got a feeling that this isn't as simple as it looks. Reading from, assigning to and reading again from the same variable in an IF statement. As far as I'm aware, the compiler will always split statements like this up into their constituent operations according to precedence and evaluates conjuncts one at a time, failing immediately when evaluating an operand to false rather than evaluating them all. If so, then I expect the code to follow the steps I wrote above.
I've used assignments in IF statements a lot and I know they work, but not with another read beforehand.
Is there any reason why this isn't good code? Personally, I think it's easy to read and the meaning is clear, I'm just concerned about the compiler maybe not producing the equivalent logic for whatever reason. Perhaps compiler vendor disparities, optimisations or platform dependencies could be an issue, though I doubt this.
...to save on code writing This is almost never a valid argument. Don't do this. Particularly, don't obfuscate your code into a buggy, unreadable mess to "save typing". That is very bad programming.
I've got a feeling that this isn't as simple as it looks. Reading from, assigning to and reading again from the same variable in an IF statement.
Correct. It has little to do with the if statement in itself though, and everything to do with the operators involved.
As far as I'm aware, the compiler will always split statements like this up into their constituent operations according to precedence and evaluates conjuncts one at a time
Well, yes... but there is operator precedence and there is order of evaluation of subexpressions, they are different things. To make things even more complicated, there are sequence points.
If you don't know the difference between operator precedence and order of evaluation, or if you don't know what sequence points are, you need to instantly stop stuffing as many operators as you can into a single line, because in that case, you are going to write horrible bugs all over the place.
In your specific case, you get away with the bad programming just because as a special case, there happens to be a sequence point between the left and right evaluation of the && operator. Had you written some similar mess with a different operator, for example ret + !(ret = lookup(), your code would have undefined behavior. A bug which will take hours, days or weeks to find. Well, at least you saved 10 seconds of typing!
Also, in both C and C++ use the standard bool type and not some home-brewed version.
You need to correct your code into something more readable and safe:
bool ret = true;
if(ret)
{
ret = lookup();
}
if(!ret)
{
fprintf(stderr, "Error in lookup()\n");
}
Is there any reason why this isn't good code?
Yes, there are a lot issues whith such dirty code fragments!
1)
Nobody can read it and it is not maintainable. A lot of coding guidlines contain a rule which tells you: "One statement per line".
2) If you combine multiple expressions in one if statement, only the first statements will be executed until the expression is defined! This means: if you have multiple expressions which combined with AND the first expression which generates false will be the last one which will be executed. Same with OR combinations: The first one which evaluates to true is the last one which is executed.You already wrote this and you! know this, but this is a bit of tricky programming. If all your colleges write code that way, it is maybe ok, but as I know, my colleagues will not understand what you are doing in the first step!
3) You should never compare and assign in one statement. It is simply ugly!
4) if YOU! already think about " I'm just concerned about the compiler maybe not producing the equivalent logic" you should think again why you are not sure what you are doing! I believe that everybody who must work with such a dirty code will think again on such combinations.
Hint: Don't do that! Never!

use of "else if" in c++

I have two questions -
(I)
code-fragment-1
if(<condition-statement>){
}
else if(<condition-statement-2>){
//statements-1
}
//statements-2
code-fragment-2
if(<condition-statement>){
}
else{
if(<condition-statement-2>){
//statements-1
}
//statements-2
}
Are the above two code fragments same?
(II) when are else ifs (in C++) used?
The only difference is in example 1 your Statement2 will get executed regardless of the conditions you check. In example 2, Statement2 will only get executed if your if condition is false. Other than that, they're basically the same.
No, in the first case you execute the else block only if the <condition-statement> is not verified AND only if <condition-statement-2> is verified.
In the second case you execute the else block simply if the <codition-statement> is not verified.
In this case are equivalent until you does not have any //statements-2.
About the question : when is the else if (in c++) used ?
Is used basically under the same conditions of all other languages​​ that have this construct.
else is executed as alternative to the related if, else-if is executed as alternative but with an 'attached' if to be verified, otherwise is not executed.
So they are not logically equivalent.
the syntax of an if is really
if(condition) statement;
What the {} really do is allow you to group together multiple statements. In your second example you only have one statement(the if) inside your {}s, so yes, both examples are the same, except //statements-2 always gets run when !=true
In your first code sample, statement-2 is executed unconditionally. In the second it is conditional. Not the same.
'else if' is generally to be preferred, because you can keep inserting or appending more of them indefinitely, or append an 'else', whereas with the other form you have to endlessly mess around with braces to get the same effect, and you risk altering the semantics, as indeed you have done in your second sample.

When should I use do-while instead of while loops? [duplicate]

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.