Why while(true) is bad practice? [closed] - loops

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
I use while true loop in many projects. It serves me well and it's not over-complicated. So, why it is a bad idea to use while true loop infinitely running background processes. Thanks for your answers.

My project leader doesn't allow this kind of loop in my code, he's arguing that it has to be replaced by while(!exit_flag)
That's very debatable. while (!exit_flag) suggests that the loop has a natural exit condition which it will reach at some specific point by itself, e.g. something counting from 0 to 100 and then leaving the loop. However, if you are writing this loop to create a permanent daemon or event loop, then the point of this loop is to keep the program running indefinitely. Nothing says indefinitely better than while (true).
There's no real technical difference between both; it's just a matter of readability and expression of intent. Of course, you'll have to square this with the people who will read that code in the end. If their policy is while (!exit_flag), so be it.

It is not a bad practice, it just means that you did not think your code through.
The condition is required to tell the loop when to finish looping. If you have a terminating point, then why not put it as a condition?
var i = 0;
while(true){
i++;
if(i == 100)
break;
}
This is fine code. But so is this:
var i = 0;
while(i != 100){
i++;
}
Both methods are correct, but if someone else is reading your code, it is much easier to see when the loop will stop iterating if it is right there in the condition.

Hm, ask the one who claimed it was "a bad idea".
What I could think of is, that any loop running indefinitely must come to an end at some point, unless, of course, you expect your program to run forever.
If while is not given any criteria to terminate, there would need to be some other kind of mechanism to terminate the loop hidden somewehere inside the looping code, like return, break or (yuck - Basic - but that's probably where the statement origins - a "Goto" statement jumping somewehere outside the loop) to terminate the loop.
Code like this may be hard to read and debug, and formerly was an indication that a programmer did not care much about writing clean code. Nevertheless nowadays with event driven applications and structured error handling (see try ... catch structures) there are clean and easy to read ways to exit any kind of loop any time, so while (true) can be used without hassles.
Greetz
ALina

Related

What code is more CPU expensive: while(*p) or while(i--)? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
What C code is more CPU expensive:
while(*pointer){
pointer++;
}
or
while(counter > 0){
pointer++;
counter--;
}
?
*pointer nominally requires a fetch from memory, and that is generally the most expensive of the operations shown in your code.
If we assume your code is compiled directly to the obvious assembly corresponding to the operations as they are described in C’s abstract machine, with no optimization, modern CPUs for desktop computers are typically capable of executing one loop iteration per cycle, except for the memory access. That is, they can increment a pointer or counter, test its value, and branch, with a throughput of one set of those per cycle.
When these operations are used in real programs, they will usually be dwarfed by the other operations being performed. Compilers are generally so good at optimization that the method used to express the loop iteration and termination has little effect on the performance—optimization will likely produce equivalent code regardless of variations in expression for differences like incrementing a counter versus iterating a pointer to some end value. (This excludes using a pointer to fetch a value from memory for testing. That does raise complications.)
If you already happen to know the size, I'd expect it to be faster to iterate for some known number of times rather than having to test a pointer each iteration to know whether or not to loop again.

Is there any ways to check statements after return in C? [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 5 years ago.
Improve this question
This code can be compiled in C:
#include <stdio.h>
int main()
{
printf("Hello World");
return 0;
printf("shouldnt allow this line");
return 1; //also this line
}
the line printf("shouldnt allow this line"); and return 1; are unreachable. Is there any ways to check this during compilation with warning messages? Also, why does the compiler allows this?
Unreachable code is not an error because:
It's often useful, especially as the result of macro expansion or functions which are only ever called in a way that makes some paths unreachable due to some of their arguments being constant or limited to particular range. For instance, with an inline version of isdigit that's only ever called with non-negative arguments, the code path for an EOF argument would be unreachable.
In general, determining whether code is unreachable is equivalent to the halting problem. Sure there are certain cases like yours that are trivial to determine, but there is no way you can specify something like "trivial cases of unreachable code are errors, but nontrivial ones aren't".
Broadly speaking, C does not aim to help a developer catch mistakes; rather, C trusts the developer to do a perfect job, just as it trusts the compiler to do a perfect job.
Many newer languages take a more active stance, aiming to protect the developer from his or herself — and plenty of C compilers will emit compile-warnings (which can typically be "promoted" to errors via command-line flags) — but the C community has never wanted the language to stop trusting developers. It's just a philosophical difference. (If you've ever run into a case where a language prevents you from doing something that seems wrong but that you actually have a good reason for, you'll probably understand where they're coming from, even if you don't agree.)

What are ways a debug statement could "fix" bugs in a program? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
In a recent interview, I was asked the following question:
You have a bug in your program, after attempting to debug it by inserting statements like printf, console.log, System.out.println, echo, etc, the bug disappears. How can this happen?
I responded with answers like the following:
You have something with side effects in the print statement, eg: System.out.println(foo.somethingWithSideEffects())
Adding printf changes the memory layout of the program, therefore it could cover adjacent memory and prevent crashes
Undefined Behavior in native code (like uninitialized values, buffer overruns, sequence points, etc)
The interviewer said those aren't the only ways that this could happen, and I couldn't think of any other ways simply adding a printf, etc could "fix" a bug in a program.
What other things could cause this to happen?
The biggest thing that comes to mind is that putting debugging code in can change the timing of the code, which can matter if there is a race condition in the code being debugged. It can be very frustrating to try to debug race conditions that disappear when inspected like this.
That could be happen because of memory overflowing , or there could be system interrupt while the program running.If you cannot really attach the debug so you may write eventlogs but it should be the last way to do i think

Best practice to find whether a for loop have been completed [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 9 years ago.
Improve this question
If I have a function f1 that scans things in a for loop:
// f1:
for(i=0;i<7;i++) {
//If conditions match Do things
break;
}
What is the recommended way to keep a flag that tracks whether the scanning has been completed entirely? If I use a flag like this:
if(i==6) {
flag=1;
}
Should I keep the flag extern/global, or should I wrap it in to some function?
What is the best way to allow it to be checked as to whether the for loop has been completely run through once?
I think it's a matter of personal style, or the style prescribed by the coning standards of your company, university, class, whatever. Having said that, I personally prefer the following "pattern" when I want to break out of a loop when a certain condition is met (or if the entire loop completed without ever meeting that condition):
int found = 0;
for (int i = 0; !found && i < max; i++)
{
if ( // condition I want )
{
found = 1;
}
}
if (found)
// do something
else
// condition was never met
I personally don't like using break statements in loops because (similar to goto) you want to avoid introducing sudden breaks from the normal flow of execution. This makes code more readable and maintainable. But this is just an opinion, so you are free to make up your mind in this regard.
For a for loop, you can check to see if all loops have completed by checking if the terminating condition has been reached. If the terminating condition has not yet been reached, then there must have been a jump out of the loop early (either with break or goto).
This tactic works perfectly so long as your loop body does not force the terminating condition to be reached as a way to leave the loop early.
So long as you are making a local decision about what to do, there is no need for anything other than local variables. Using global variables to store flags is only useful for flags that intend to affect global behavior.

While vs. for: what is the best? [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 9 years ago.
Improve this question
If I can do a cycle with for and while both, which should I choose?
[for]
int num = 10;
int i;
for (i=0; i<num; i++)
{
/* ... */
}
[while]
int num = 10;
int i = num;
while ( i-- )
{
/* ... */
}
The choice between for and while is just matter of clarity:
K&R . Chapter 1. The For statment:
The choice between while and for is arbitrary, based on which seems
clearer. The for is usually appropriate for loops in which the initialization and
increment are single statements and logically related, since it is more compact
than while and it keeps the loop control statements together in one place.
Performance, of course, depends on the implementation in the language used. However, in most cases and with most compilers, the generated code from both loops will pretty much be the same.
A rule of thumb would be to use while when you don't know exactly how many times you want to iterate. In your example, it doesn't make much difference. Use what's clearer to you.
And yes, declarations in the for loop are only allowed in newer versions of C (C99).
Usually, you'd use a for loop for something like that because you know before you start the loop how many times you need the loop to run. while loops are more for when you don't know how many times you're going to have to repeat, and something that the user inputs or some random int will change it
In the example above, you should use a for loop since it clearly expresses the intent of what you intend. "Do this loop num times". Also, it is much simpler for the compiler to potentially optimize for loops into vector assembly operations.
You should use a while loop when you have a clearly expressible condition like
"Read lines until EOF" or some other condition that doesn't have an easily enumerable solution.
Also, I consider it poor practice to depend on the fact that 0 is false. You should clearly write the condition that exits the loop.
Every program solve in while loop that can be solved in for loop,but for loop suitable for:-
1--> If i know how many time the loop Will execute and while loop is suitable for if i don't know how many time the loop will be executed.

Resources