Do while loop with a cout statement - c++

So I have a general question about the do/while loop. I'm learning C++ and I know that you can write something like that:
do{
....
} while(a<10 && cout<<"message");
The point is, that i know this is possible in c++, but do we really do that? I mean, the "cout" thing inside the while?

Your while loop is equivalent to
do {
...
cout << "message";
while(a < 10 && cout);
because cout << ... returns cout again.
Then, the question is, what does it mean to write statements like
while( cout );
or
if (cout) ...
The cout object has a conversion to boolean which is used here. It's implementation is checking !fail(), so
if (cout) ...
is equivalent to
if (!cout.fail()) ...
and
do { ... }
while(cout);
is equivalent to
do { ... }
while(!cout.fail());
Finally, fail returns true if the stream failed to produce output.

The fact is some people do this (i.e. run a function as part of the condition evaluation). It makes sense in a shell script, but if you're not using a shell script, it's sometimes not clear what the return value is for some functions. I couldn't tell you what cout<<"message" returns offhand, but I do know that if you write it inside the loop body, it would do what I want, and it would 'throw away' the return value if I don't use it.
To write cleaner code that others including your future-self can understand, I would only evaluate conditions which obviously return true/false as opposed to "0/not-0", or "0/1" which may different in different languages.
Bottom line is, let the compiler make things more efficient for you, and code for other people, not for the compiler.

If you want to perform the output after testing the condition, you would need to either do that or add another condition test inside the loop and maintain both of them, which is a bug waiting to happen.
do {
if (a < 10)
cout << "message";
} while (a < 10);
It's rare to see cout << by itself in any condition though, as you can usually assume that it will succeed unless your machine is on fire.
On the other hand the extraction operator, >>, usually belongs inside a condition;
while (cin >> x)
is idiomatic C++.

Related

What would happen if I used a cout statement as the condition for an if statement?

So, my programming instructor asked me to try putting a cout-statement as the condition for an if-statement and see what happens. I tried it (just made a random code) and didn't notice anythimg special. Here's the code.
#include<iostream>
using namespace std;
int main()
{
int x=1;
int y=2022;
if(cout<<"Covid")
{
cout << "\n Us \n";
x=y;
cout << x;
}
}
The output is simply
Covid
Us
2022
What I don't understand is why this would be used. From my amateur understanding, even if I used an else-statement or any amount of else-if statements, they wouldn't run, since the condition for the if-statement is self-fulfilling. I could the simply write the whole code directly without using an if-statement. What then, could be the purpose of using an if-statement? Any general use?
Prior to C++11, when you write if(cout << "Covid"), there is an implicit conversion to void*. This value is unspecified by the C++ standard, other than if the stream is in an error state, then nullptr is returned.
From C++11, the implicit conversion is to bool. false denotes the stream is in an error state, true otherwise.
Note that you must have imbued a very funky iostream-derived object indeed for the output to be "Pakistan" given your input!

Multiple return statements

I am currently reading "A tour of C++" from Bjarne Stroustup, and I saw the following example:
bool accept()
{
cout << "Do you want to proceed (y or n)?\n"; // write question
char answer = 0; // initialize to a value that will not appear on input
cin >> answer; // read answer
if (answer == 'y')
return true;
return false;
}
I thought using multiple return statements wasn't recommended. Wouldn't it be better practice in this case to create a bool variable, initialize it to 0 and then modify it in the if condition, to finally return the value of this boolean variable? Or I am just making things up.
No, you're not entirely making things up, and no there is no recommendation of such that I know of.
Snippet According to your recommendation:
Int accept()
{
Int result=0;
cout << "Do you want to proceed (y or n)?\n"; // write question
char answer = 0; // initialize to a value that will not appear on input
cin >> answer; // read answer
if (answer != 'y')
result=1;
return result;
}
Looking closer you will notice no difference between the snippet above and the one you found in the book, they book use validation, the difference is the data-type used.
Now, it will be more easy to use a boolean if you need to simple use the function accept like below:
if(accept()) /*do something*/;
Rather than:
if(accept()==0) /*do something*/
Either way, you're good to go.
Another thing to consider is the size of your data-type, boolean is just 1bit while int is 4bytes so comparison time complexity will obviously be different but you will most likely never notice the difference.
Edit:
In java boolean is 1bit as said above but since it's c++, because of the issue of 1bit not addressable, it only make more sense to make it 8bit and then it can be given an address in the memory.
So, in C++ boolean is also 1byte or 8bit, and so the comparison time difference is not a thing to consider.
Both approaches are possible, but you will usually see the version using multiple return values. Take a look how this part of the code works:
if (answer == 'y')
return true;
return false;
At first you may see two branches in which the executed code can go, based on the value of answer. First one is connected with y choice, and the other one with anything else. This code could also look like this:
if (answer == 'y')
return true;
else
return false;
But it makes the program a bit more complicated - there is one more jmp instruction in assembly code, which means that the code is just a bit more complex, but its functionality is exactly the same as of the previous version.
Now, we can add the bool variable and let's see how it will look like:
bool is_answer_positive = false;
if (answer == 'y')
is_answer_positive = true;
else // we can get rid of this statement
is_answer_positive = false; // as we have defined variable earlier
return is_answer_positive;
The first thing which makes the code a bit more complex is a new variable, which does not add any vital value to the code, I would say it makes it only more complicated. This is the first instruction which makes the code bigger, but not better. Then if/else works similarly to the second version, but you also assign some values to the is_answer_positive, which also makes the code bigger, but not better. At the end, you return the value you got from if/else statement and the code is done. We can get rid of else statement, as is_answer_positive was initialized to be false, but this is still not the best solution.
Comparing those three possibilities: first version is the most used one, it is clear and probably the simplest, second version adds extra jump, which is unnecessary at all, and the third version adds extra variable, which makes the code a bit harder to read.

Bug in c++ program during a simple loop

I'm trying to solve this problem as few lines of code as possible.
problem statement:
someone managed to say hello if several letters can be deleted from the typed word so that it resulted in the word "hello"... I'm testing if he could or not
#include <iostream>
int main() {
char c;
int i=0;
while(i!=5 && (cin>>c) && c!='\n'){
if(c=="hello"[i])
i++;
}
cout<<((i==5)?"YES":"NO");
}
There's a bug when it should print "NO". The program waits for more input. I think the loop doesn't finish until i==5 but it never finishes when c=='\n'.
Before you pack your program to minimize the LOC (and I assume that you have a really good reason to care about this because otherwise it is a foolish thing to do) make it right!
Try putting the i != 5 test BEFORE the cin >>c test. Otherwise you read one extra character when you do get a "hello"
Edit: Just to be clear, the code in the question has now been modified to incorporate this suggestion.
You have a while loop there
while(i!=5 && (cin>>c) && c!='\n')
{ ... }
...which you can rewrite for easier debugging. In general, instead of any loop...
while (X)
{ Y }
...you can also write...
while (true)
{
if (!X) break;
Y
}
For your loop, that would be this code:
while (true)
{
if (!(i!=5 && (cin>>c) && c!='\n'))
break;
...
}
Now, I assume you are aware of the short circuit evaluation of the logical AND operator. If not, search the web for that term! With that knowledge, you can rewrite your loop like this:
while (true)
{
if (!(i!=5))
break;
if (!(cin>>c))
break;
if (!(c!='\n'))
break;
...
}
Of course, you can still simplify a few double negations there, but the idea should be clear. This change now allows you to e.g. step through this in a debugger to evaluate each loop exit condition separately. This is important, because the second loop condition also has side effects! In addition, you could e.g. add some debug output that tells you the reason why the loop was exited. Further, for the check that has side effects, you can inspect the intermediate state (or output the state, if you prefer that way), which will give you further insight on the issue.
Lastly, all >> operators on istreams by default skip whitespace, which includes spaces, tabs and newlines, so your last check will never cause the loop to exit. You can tell the stream to not skip whitespace though, if that's what you want. How to do that should be really simple to find out using another websearch. ;)

execution order of loops in C

this is probably a very noob question but I was what the result of this would be:
int someVariable = 1;
while (callFunction(someVariable));
if (someVariable = 1) {
printf("a1");
} else {
printf("a2");
}
callFunction (int i) {
while (i< 100000000) {
i++;
}
return 0;
}
so when you hit the while loop
while (callFunction(someVariable));
does a thread wait at that loop until it finishes and then to
if(someVariable == 1) {
printf("a1");
} else {
printf("a2");
}
or does it skip and move to the if condition, print "a2" and then after the loop has finished goes through the if condition again?
UPDATE: This isn't ment to be valid c code just psuedo, maybe I didn't word it right, basically what I'm trying to figure out is what the different between a loop like while (callFunction(someVariable)); is vs
while (callFunction(someVariable)){}
i also changed the bolded part in my code i.e ** int someVariable = 1; **, I was doing an endless loop which wasn't my intention.
The code inside a function is executed sequentially, by a single thread. Even if you send an other thread to your function it will execute it sequentually as well.
This is true to 99% of programming languages now days.
UPDATE
basically what I'm trying to figure out is what the different between a loop like while (callFunction(someVariable)); is vs while (callFunction(someVariable)){}
No practical difference. ; delimits an empty statement, { } is a scope without statements. Any compiler can be expected to produce identical code.
Of course, if you want to do something in each iteration of the loop, { } creates a "scope" in which you can create types, typedefs and variables as well as call functions: on reaching the '}' or having an uncaught exception, the local content is cleaned up - with destructors called and any identifiers/symbols use forgotten as the compiler continues....
ORIGINAL ANSWER
This...
callFunction(int i){
while (i< 100000000){
i++;
}
return 1;
}
...just wastes a lot of CPU time, if the compiler's optimiser doesn't remove the loop on the basis that it does no externally-visible work - i.e. that there are no side-effects of the loop on the state of anything other that "i" and that that's irrelevant because the function returns without using i again. If always returns "1", which means the calling code...
while (callFunction(someVariable));
...is equivalent to...
while (1)
;
...which simply loops forever.
Consequently, the rest of the program - after this while loop - is never executed.
It's very hard to guess what you were really trying to do.
To get better at programming yourself - understanding the behaviour of your code - you should probably do one or both of:
insert output statements into your program so you can see how the value of variables is changing as the program executes, and whether it's exiting loops
use a debugger to do the same
Your code contains an endless loop before any output:
while (callFunction(someVariable));
Did you mean for the ; to be there (an empty loop), or did you
mean something else? Not that it matters: callFunction
always returns 1, which is converted into true. (If you
really want the loop to be empty, at least put the ; on
a separate line where it can be seen.)
If you do get beyond the while (because you modify some code
somewhere), the if contains an embedded assignment; it's
basically the same as:
if ( (someVariable = 1) != 0 )
Which is, of course, always true. (Most C++ compilers should
warn about the embedded assignment or the fact that the if
always evaluates to true. Or both.)
If your loop completes (it would be sequentially yes, if you fix it), it will print 'a1', since you're doing an assignment in the if, which will always return 1, which evaluates to 'true' for conditionals.

Is there ever a need for a "do {...} while ( )" loop?

Bjarne Stroustrup (C++ creator) once said that he avoids "do/while" loops, and prefers to write the code in terms of a "while" loop instead. [See quote below.]
Since hearing this, I have found this to be true. What are your thoughts? Is there an example where a "do/while" is much cleaner and easier to understand than if you used a "while" instead?
In response to some of the answers: yes, I understand the technical difference between "do/while" and "while". This is a deeper question about readability and structuring code involving loops.
Let me ask another way: suppose you were forbidden from using "do/while" - is there a realistic example where this would give you no choice but to write unclean code using "while"?
From "The C++ Programming Language", 6.3.3:
In my experience, the do-statement is a source of errors and confusion. The reason is that its body is always executed once before the condition is evaluated. However, for the body to work correctly, something very much like the condition must hold even the first time through. More often than I would have guessed, I have found that condition not to hold as expected either when the program was first written and tested, or later after the code preceding it has been modified. I also prefer the condition "up front where I can see it." Consequently, I tend to avoid do-statements. -Bjarne
Avoiding the do/while loop is a recommendation included in the C++ Core Guidelines as ES.75, avoid do-statements.
Yes I agree that do while loops can be rewritten to a while loop, however I disagree that always using a while loop is better. do while always get run at least once and that is a very useful property (most typical example being input checking (from keyboard))
#include <stdio.h>
int main() {
char c;
do {
printf("enter a number");
scanf("%c", &c);
} while (c < '0' || c > '9');
}
This can of course be rewritten to a while loop, but this is usually viewed as a much more elegant solution.
do-while is a loop with a post-condition. You need it in cases when the loop body is to be executed at least once. This is necessary for code which needs some action before the loop condition can be sensibly evaluated. With while loop you would have to call the initialization code from two sites, with do-while you can only call it from one site.
Another example is when you already have a valid object when the first iteration is to be started, so you don't want to execute anything (loop condition evaluation included) before the first iteration starts. An example is with FindFirstFile/FindNextFile Win32 functions: you call FindFirstFile which either returns an error or a search handle to the first file, then you call FindNextFile until it returns an error.
Pseudocode:
Handle handle;
Params params;
if( ( handle = FindFirstFile( params ) ) != Error ) {
do {
process( params ); //process found file
} while( ( handle = FindNextFile( params ) ) != Error ) );
}
do { ... } while (0) is an important construct for making macros behave well.
Even if it's unimportant in real code (with which I don't necessarily agree), it's important for for fixing some of the deficiencies of the preprocessor.
Edit: I ran into a situation where do/while was much cleaner today in my own code. I was making a cross-platform abstraction of the paired LL/SC instructions. These need to be used in a loop, like so:
do
{
oldvalue = LL (address);
newvalue = oldvalue + 1;
} while (!SC (address, newvalue, oldvalue));
(Experts might realize that oldvalue is unused in an SC Implementation, but it's included so that this abstraction can be emulated with CAS.)
LL and SC are an excellent example of a situation where do/while is significantly cleaner than the equivalent while form:
oldvalue = LL (address);
newvalue = oldvalue + 1;
while (!SC (address, newvalue, oldvalue))
{
oldvalue = LL (address);
newvalue = oldvalue + 1;
}
For this reason I'm extremely disappointed in the fact that Google Go has opted to remove the do-while construct.
The following common idiom seems very straightforward to me:
do {
preliminary_work();
value = get_value();
} while (not_valid(value));
The rewrite to avoid do seems to be:
value = make_invalid_value();
while (not_valid(value)) {
preliminary_work();
value = get_value();
}
That first line is used to make sure that the test always evaluates to true the first time. In other words, the test is always superfluous the first time. If this superfluous test wasn't there, one could also omit the initial assignment. This code gives the impression that it fights itself.
In cases such like these, the do construct is a very useful option.
It's useful for when you want to "do" something "until" a condition is satisfied.
It can be fudged in a while loop like this:
while(true)
{
// .... code .....
if(condition_satisfied)
break;
}
(Assuming you know the difference between the both)
Do/While is good for bootstrapping/pre-initializing code before your condition is checked and the while loop is run.
In our coding conventions
if / while / ... conditions don't have side effects and
varibles must be initialized.
So we have almost never a do {} while(xx)
Because:
int main() {
char c;
do {
printf("enter a number");
scanf("%c", &c);
} while (c < '0' || c > '9');
}
is rewritten in:
int main() {
char c(0);
while (c < '0' || c > '9'); {
printf("enter a number");
scanf("%c", &c);
}
}
and
Handle handle;
Params params;
if( ( handle = FindFirstFile( params ) ) != Error ) {
do {
process( params ); //process found file
} while( ( handle = FindNextFile( params ) ) != Error ) );
}
is rewritten in:
Params params(xxx);
Handle handle = FindFirstFile( params );
while( handle!=Error ) {
process( params ); //process found file
handle = FindNextFile( params );
}
It's all about readability.
More readable code leads to less headache in code maintenance, and better collaboration.
Other considerations (such as optimization) are, by far, less important in most cases.
I'll elaborate, since I got a comment here:
If you have a code snippet A that uses do { ... } while(), and it's more readable than its while() {...} equivalent B, then I'd vote for A. If you prefer B, since you see the loop condition "up front", and you think it's more readable (and thus maintainable, etc.) - then go right ahead, use B.
My point is: use the code that is more readable to your eyes (and to your colleagues'). The choice is subjective, of course.
First of all, I do agree that do-while is less readable than while.
But I'm amazed that after so many answers, nobody has considered why do-while even exists in the language. The reason is efficiency.
Lets say we have a do-while loop with N condition checks, where the outcome of the condition depends on the loop body. Then if we replace it with a while loop, we get N+1 condition checks instead, where the extra check is pointless. That's no big deal if the loop condition only contains a check of an integer value, but lets say that we have
something_t* x = NULL;
while( very_slowly_check_if_something_is_done(x) )
{
set_something(x);
}
Then the function call in first lap of the loop is redundant: we already know that x isn't set to anything yet. So why execute some pointless overhead code?
I often use do-while for this very purpose when coding realtime embedded systems, where the code inside the condition is relatively slow (checking the response from some slow hardware peripheral).
This is cleanest alternative to do-while that I have seen. It is the idiom recommended for Python which does not have a do-while loop.
One caveat is that you can not have a continue in the <setup code> since it would jump the break condition, but none of the examples that show the benefits of the do-while need a continue before the condition.
while (true) {
<setup code>
if (!condition) break;
<loop body>
}
Here it is applied to some of the best examples of the do-while loops above.
while (true) {
printf("enter a number");
scanf("%c", &c);
if (!(c < '0' || c > '9')) break;
}
This next example is a case where the structure is more readable than a do-while since the condition is kept near the top as //get data is usually short yet the //process data portion may be lengthy.
while (true) {
// get data
if (data == null) break;
// process data
// process it some more
// have a lot of cases etc.
// wow, we're almost done.
// oops, just one more thing.
}
It is only personal choice in my opinion.
Most of the time, you can find a way to rewrite a do ... while loop to a while loop; but not necessarily always. Also it might make more logical sense to write a do while loop sometimes to fit the context you are in.
If you look above, the reply from TimW, it speaks for itself. The second one with Handle, especially is more messy in my opinion.
Read the Structured Program Theorem. A do{} while() can always be rewritten to while() do{}. Sequence, selection, and iteration are all that's ever needed.
Since whatever is contained in the loop body can always be encapsulated into a routine, the dirtiness of having to use while() do{} need never get worse than
LoopBody()
while(cond) {
LoopBody()
}
I hardly ever use them simply because of the following:
Even though the loop checks for a post-condition you still need to check for this post condition within your loop so that you don't process the post condition.
Take the sample pseudo code:
do {
// get data
// process data
} while (data != null);
Sounds simple in theory but in real world situations it would probably turn out to look like so:
do {
// get data
if (data != null) {
// process data
}
} while (data != null);
The extra "if" check just isn't worth it IMO. I have found very few instances where it's more terse to do a do-while instead of a while loop. YMMV.
In response to a question/comment from unknown (google) to the answer of Dan Olson:
"do { ... } while (0) is an important construct for making macros behave well."
#define M do { doOneThing(); doAnother(); } while (0)
...
if (query) M;
...
Do you see what happens without the do { ... } while(0)? It will always execute doAnother().
A do-while loop can always be rewritten as a while loop.
Whether to use only while loops, or while, do-while, and for-loops (or any combination thereof) depends largely on your taste for aesthetics and the conventions of the project you are working on.
Personally, I prefer while-loops because it simplifies reasoning about loop invariants IMHO.
As to whether there are situations where you do need do-while loops: Instead of
do
{
loopBody();
} while (condition());
you can always
loopBody();
while(condition())
{
loopBody();
}
so, no, you never need to use do-while if you cannot for some reason. (Of course this example violates DRY, but it's only a proof-of-concept. In my experience there is usually a way of transforming a do-while loop to a while loop and not to violate DRY in any concrete use case.)
"When in Rome, do as the Romans."
BTW: The quote you are looking for is maybe this one ([1], last paragraph of section 6.3.3):
From my experience, the do-statement is a source of error and confusion. The reason is that its body is always executed once before the condition is tested. For the correct functioning of the body, however, a similar condition to the final condition has to hold in the first run. More often than I expected I have found these conditions not to be true. This was the case both when I wrote the program in question from scratch and then tested it as well as after a change of the code. Additionally, I prefer the condition "up-front, where I can see it". I therefore tend to avoid do-statements.
(Note: This is my translation of the German edition. If you happen to own the English edition, feel free to edit the quote to match his original wording. Unfortunately, Addison-Wesley hates Google.)
[1] B. Stroustrup: The C++ programming language. 3rd Edition. Addison-Wessley, Reading, 1997.
consider something like this:
int SumOfString(char* s)
{
int res = 0;
do
{
res += *s;
++s;
} while (*s != '\0');
}
It so happens that '\0' is 0, but I hope you get the point.
My problem with do/while is strictly with its implementation in C. Due to the reuse of the while keyword, it often trips people up because it looks like a mistake.
If while had been reserved for only while loops and do/while had been changed into do/until or repeat/until, I don't think the loop (which is certainly handy and the "right" way to code some loops) would cause so much trouble.
I've ranted before about this in regards to JavaScript, which also inherited this sorry choice from C.
Well maybe this goes back a few steps, but in the case of
do
{
output("enter a number");
int x = getInput();
//do stuff with input
}while(x != 0);
It would be possible, though not necessarily readable to use
int x;
while(x = getInput())
{
//do stuff with input
}
Now if you wanted to use a number other than 0 to quit the loop
while((x = getInput()) != 4)
{
//do stuff with input
}
But again, there is a loss in readability, not to mention it's considered bad practice to utilize an assignment statement inside a conditional, I just wanted to point out that there are more compact ways of doing it than assigning a "reserved" value to indicate to the loop that it is the initial run through.
I like David Božjak's example. To play devil's advocate, however, I feel that you can always factor out the code that you want to run at least once into a separate function, achieving perhaps the most readable solution. For example:
int main() {
char c;
do {
printf("enter a number");
scanf("%c", &c);
} while (c < '0' || c > '9');
}
could become this:
int main() {
char c = askForCharacter();
while (c < '0' || c > '9') {
c = askForCharacter();
}
}
char askForCharacter() {
char c;
printf("enter a number");
scanf("%c", &c);
return c;
}
(pardon any incorrect syntax; I'm not a C programmer)