Disadvantage of for loop [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
What are the actual disadvantages of for loop? No, I mean seriously. There must be something right. There are while and do while loops, both effective, yet we have a for loop. There must be some disadvantage in for loop due to which while and do while were developed, right?

No, while loops are the basic structure for making loops, based on conditional gotos or assembly jumps if you will. However, because the following code was being written all the time to go through arrays:
int i = 0;
while (i < N)
{
//do something, probably access an array
i++;
}
They created a cleaner, more readable, way to do this:
for(int i = 0; i < N; i++)
{
//do something
}
This is an example of what is called Syntactic sugar.
Because there is no inherent reason for these kind of things to exist a famous quote of Alan Perlis goes "syntactic sugar causes cancer of the semicolon".
That being said, you always have to strive for more readable codes, so go for it.

No disvantages at all. I think that Go language did away with while(), it just has for().

Even though while(cond){...} and for(; cond; ){...} are equivalent. However, writing a for loop in this way without a counter and incremental expression is weird. To make your code easier and readable, you should use the for-loop in its original and natural format. i.e., for (counter; cond; expr). If you can iterate your loop's body according to the evaluation of a particular expression, then you should stick with a while loop.

The disadvantage may be that with the only for loop the "while(cond) { /* do something*/ }" were been invalid code... :-)

Related

Is there a speed difference between an if check and a while check [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 3 years ago.
Improve this question
I am solving a question where theres a main while loop with condition being int i =0; while(i<vector.size()) and inside this while loop I have another while loop that increases i if current element in the index is odd. Such as while(i<vector.size()&&vector[i]%2!=0 )i++;. My question is if i replaced the second while loop with and if statement, would my performance be different? which would be faster and why? I know Big O complexity would be O(N) in both cases but I am talking about real world speed. I am using c++ if it matters. Does the compiler make optimizations for the while loop/ is there more checks to do in an if statement and so on? This is just a question out of curiosity.
int i=0;
vector<int> temp(1000,1);
while(i<temp.size())
{
while(i<temp.size()&&temp[i]%2!=0)
{
i++;
}
}
or
int i=0;
vector<int> temp(1000,1);
while(i<temp.size())
{
if(i<temp.size()&&temp[i]%2!=0)
{
i++;
}
}
From a performance point of view, the difference is negligible. And any decent compiler will transform both snippets of your code to (nearly) identical assembly depending on your optimization settings.
From a design point of view, it makes no sense to have two loops or a nested loop and an if inside loop in the first place. As you could easily rewrite your condition in just one loop.
When it comes to performance comparison questions the first thing to do is benchmark the code yourself. Godbolt is a great website to check the produced assembly differences for different codes and compilers.
Really though, unless you're working with very very very specific software and hardware that can not afford to delay a few clock cycles then this kind of optimization is premature. Unless, you know your platform and code very well the compiler will outsmart you in generating fast assembly. Just focus on getting correct and readable code.
It appears that your outer while() loop becomes infinite if any of the element is even (i will not be incremented). What is the performance of an infinite loop?

What is better for performance? Infinitive loop with if or normal loop? [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 3 years ago.
Improve this question
i often see game engines doing:
for(;;) if(!frame()) break;
Why arent they just writing:
while(frame());
or if they want to use for:
for(;frame(););
is it possible that with for(;;) or while (true) the compiler can optimize more because the condition is always true?!
This is horses for courses.
Any good optimising compiler will generate the same code in these circumstances.
Old-fashioned folk rely heavily on for(;;) as most mainsteam compilers don't generate a warning for that when warnings are set "normally". In my opinion at least while(frame()); is a little clearer although some folk don't like empty loop bodies, and the loop body of the first way is not empty.
From cppreference on for loops:
The above syntax [a for loop] produces code equivalent to:
{
init_statement
while ( condition ) {
statement
iteration_expression ;
}
}
Compilers do not read cppreference, but they also do know that each for loop can be written as a while loop and vice-versa.
The reason you see it often is probably a matter of convention. And we can only guess why it was choosen. Let me speculate...
Consider this loop:
for (int i=0;i < N; ++i);
{
// do something
}
Can you spot the mistake? Good compiler warn about it, but in my opinion the potential for such mistakes or to confuse a loop without body with such mistake is reason enough to avoid loops without body when it is possible for no cost.
is it possible that with for(;;) or while (true) the compiler can
optimize more because the condition is always true?!
No, effectively the condition is the same in all three versions.

Why else condition is needed in c++ for good coding practice even if we have nothing to write in there? [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 3 years ago.
Improve this question
I have seen else condition even if there is nothing inside it in many standard code documents. Why is that? Why should we use else even there is nothing to write in there as a good practice?
int a=1,b=2;
if(a)
{
a=a+b;
}
else
{
// Why we need this even there is nothing to write
}
Code standards are not global, these vary with the group, organization or community. Some people think it is more readable and maintainable this way, some think otherwise.
In my opinion, it is one of those rules made up by people who have too much free time on their hands.
I mean just look at it
if(condition) { do something }
else { }
How is that even more readable and maintainable. It is just adding some extra trash code.
I think one should avoid such documents for the sake of code.
However, if you work with people who follow the same standards either convince them to drop this out of standards or just walk away slowly :)

How do I know if my approach to code is good or bad? [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 6 years ago.
Improve this question
I am a c++ programmer. I was trying Sieve of Eratosthenes. My program is calculating primes upto a million quickly and is in accordance to what Sieve actually is. But how do I know if there was a better way to code it or if my way of coding is bad.
Many people say try to google and compare it with how other solve it. I am not in support of that because as everyone knows, every programmer has different approach to a problem.
Link to my code: http://pastebin.com/qkrBpd29
Edit: I just realised that your code isn't really using any of C++'s features, Only std::cin and std::cout. It's basically C code. My response below was assuming that you were working with C++.
From looking at your code I would advice that think about memory management. You've written objects with resources that don't have destruction. You are writing global functions that accept a node object, when these functions should be class functions.
Learn about smart pointers std::unique_ptr and std::shared_ptr from #include <memory> and where to use them appropriately.
If possible whenever you need something on the heap, declare something on the stack to try and ensure that it is cleaned up afterwards, this is know as RAII. (Sidenote, RAII, is a terrible name that has stuck, don't worry about what it stands for since it's not very descriptive.)
Read Effective C++ by Scott Meyers and Effective Modern c++ Scott Meyers.
There are also some great lectures from cppcon on youtube.
Essentials of Modern C++ Style
Writing Good C++14
If I understood correctly, then your implementation is based on lists. This is not very good because you have to get to the correct positions before you can delete. I think it's much simpler to use an array instead (sorry, java code):
boolean[] isNotPrime = new boolean[MAX + 1];
// we know 2 is prime, it's enough to look at the odd numbers
primes.add(2); // list of primes
for (int i = 3; i < isNotPrime.length; i += 2) {
if (isNotPrime[i])
continue;
primes.add(i);
for (int j = 3 * i; j < isNotPrime.length; j += 2 * i)
isNotPrime[j] = true;
}
No code is perfect and there are many right ways to do things but asking yourself or others the following questions should help you.
Is my code correct? Does it produce the right answers all the time?
Is my code efficient?
Is my code maintainable? Can someone else build on it easily without having to rewrite the whole thing?
struct Node{
int a;
Node* linkl;
Node* linkr;
}*top,*rear;
top and rear are globals. Not good. Globals need to be very rare and you
don't need them here.

if-else or early return [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 2 years ago.
Improve this question
Sometimes I like to use early return statements to prevent nesting if statement, which I find makes for less readable code.
I am wondering if there is any objective or overwhelming general consensus as two which of the following patterns is better practice? I don't think this is a subjective question, since what I am really asking is there a near objective preference.
void func() {
if (a) {
do b
}
else {
do c
}
}
or
void func() {
if (a) {
do b
return;
}
do c
}
Frankly, I recommend the second one.
The second is more clear to understand
When some else modify the code more easy to understand is the first place.
Maybe the first is more clear in math but not in human being.
I would opt for the first version. I was actually given a lengthy explanation several years ago regarding this.
The two examples, as your wrote them now, are functionally identical. If the a condition be true, then the logic in the first if condition will execute, and the function will return. However, have a closer look at the second scenario:
void func() {
if (a) {
do b
return;
}
do c
}
Right now, should the first if fire, the function would return, otherwise c would execute. However, consider that at some point down the line a programmer decides to refactor the method for some reason. If he were to take out the return statement, then the logic for c would also execute if a were true. This may seem far-fetched, but it could happen more easily than you might think. On the other hand, if you use a full if-else, then even a refactor of the if condition would never result in the c logic evaluating at the same time.
The first is better. Simply put,it helps another developer to understand that c compiles because the condition is false. It also prevents other people from making damaging changes to your code. That said,they are both correct and would both work just fine