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
Related
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?
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.
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 :)
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
Today, me and my colleague have a disagreement on a subject :
Which of the following is "cleaner" and why ? :
bool check(){
if(!test to do){
return false;
}
if(!other test to do){
return false;
}
return true;
}
Or:
bool check(){
bool result = true;
if(!test to do){
result = false;
}
if(!other test to do){
result = false;
}
return result;
}
In my opinion, it doesn't matter because of compilation process.
It almost doesn't matter functionally, because of the compilation process.
Some older texts recommend a single return, i.e. your second example, as they say the logic of the function is easier to trace.
Personally I dislike clutter and find the first example easier to read. You still have to think about and reason about the function in either case, just the first doesn't involve an additional variable and potentially more if/else flow clutter.
The first one doesn't always evaluate the second condition, though, which may be of interest to you if it has performance penalties, or side effects.
Furthermore, individual return statements are easier for the compiler to elide (not that it matters here).
But otherwise it's completely subjective.
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... :-)