While vs. for: what is the best? [closed] - c

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.

Related

Math operation in the test expression of the `for` loop - perfomance, optimisation [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
I am interested, which of these forms of the for loop test expression is more right (from the point of the performance and the good code practice):
for(i = 0; i < size - 1; i++) {
do something
}
or
int decreased_size = size - 1;
for(i = 0; i < decreased_size; i++) {
do something
}
Is the test expression size - 1 calculated every time in the first example or does the compiler optimize it to the constant value, so there is no need to creating an additional variable decreased_size?
I was creating an additional variable all the time, but now, looking at the others solutions on the Codeforces, I doubts - whether it makes sense?
Compiler: GCC version 5.4.0 20160609
No one makes more sense than other. Indeed, with optimization, it produces same code : https://godbolt.org/g/vzVJVF
Secondly, time consumed by size-1 is, in most case, negligible vis-a-vis of time consumed by action in loop, so optimize this part has a really small effect on system.
In conclusion, optimize only when it's needed (so you see that there is an time/memory issue). In every day, prefer a readable, easy to understand code.
I agree with #Garf365. If you also look at https://www.tutorialspoint.com/assembly_programming/assembly_loops.htm you will see that loop count is loaded into register before loop starts and so size-1 has to be computed and loaded only once.

why include a for loop inside a for loop [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 7 years ago.
Improve this question
i have seen some code where programmers include a for loop inside a for loop.for example
for(i=0; i<n; i++){
for(j=0;j<n;j++)
Why is this important?
Please tell me when do I need to include this nested loop in my code.
You dont use nested loops because they are important. You use it because the program requires it. Try to understand the logic of the program you are referring. Then you will understand why they are used. You can read about nested loops here.
It is NOT important. You simply use nested for loops when you feel you need to. Some good examples would be sorting algorithms. You can't sort an entire vector in one loop, so you need a nested loop to ensure that you sort the entire vector, not just the elements from the first iteration.
Here is a list with some sorting algorithms. Take a look at how they use nested for loops to see why it is sometimes required.
Another good example of when to use nested loops is when you need to iterate through a matrix. A single for loop would let you check only the first line from the matrix, so you add a secondary loop to iterate through every single line, not just one.
It is not important to use nested loop in every program. It depends upon the requirement of the program.
You can understand the concept of nested programming HERE

Why while(true) is bad practice? [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
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

Is using i++ (or ++i) really a good practice? [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 8 years ago.
Improve this question
I know the differences between i++ and ++i (like this) if I want to use their new values. And I saw many examples in The C Programming Language (K&R) use expressions like s[i++] = c;. Sometimes, I come across codes (shown following) make me confused and this style seems highly regraded by them.
while (*string1++ = *string2++); //in c
And in this post, Jon 'avoid using' this style.
So my question is to use i++ (or ++i) like above code a good practice? If not, in which situation should I use it (Just when I don't use its new valve ?)
By itself, i++ is a clear, idiomatic expression for the idea of incrementing a variable. By itself, it is as clear as it gets. A computer language was named after this idiom (C++).
Jon wasn't saying to avoid "i++"; he was saying to avoid combining it with other expressions that would complicate things, where the increment operation was a "side effect". Like:
arr2[++j] = arr[++i]; // now what the heck is going on? I have to stop and look.
In that case, it is more reasonable to avoid it, and I agree with him. As you start to tweak code, and move things around, or add logic, the increment might go away, move, become redundant etc. and it is often better to perform the increment on a line by itself, or in a loop header instead.
The interesting thing about the ++ operator, besides that it Was a genius idea, is that the prefix and postfix alternatives encode more than just "i = i + 1", they encode an additional evaluation of the left or right hand side of the assignment, so to speak. (Or you could think of it as pre/post evaluation).
So ++i is functionally:
i = i + 1; return i
and i++ is functionally:
temp = i; i = i + 1; return temp
This difference causes additional "trouble" by hiding bugs, and you can see why, if the compiler doesn't optimize the generated code, they have different performance ramifications.
It seems to largely be a matter of personal style and the requirements of the situation.
It's more concise to write i++ compared to i+=1 or i=i+1, and it can help you to remove lines of code that don't communicate an essential fact of the algorithm.
Of course, Jon Skeet is right (as usual) that it can make your code more difficult to understand: mentally distinguishing between ++i and i++ is another cycle your brain has to go through to understand what's going on.
There are situations where more granularity in your code is what you want; there are times when you don't care as much. There aren't really any hard-and-fast rules.
Of course, having said that, I would personally recommend not using i++ or ++i as function arguments (i.e. foo(i++)), since that can introduce some very hard-to-track bugs if you're not very careful, or mixing them with other operators (i.e. Bryan Chen's example of i++ + k++).

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.

Resources