Revisit curly braces and performance in C++ [duplicate] - c++

This question already has answers here:
Does adding unnecessary curly brackets { } in a c++ program slow it down at all?
(3 answers)
Closed 6 years ago.
I know that this question has been asked and answered here, among other places, but none of the answers touched on the reason I was given (years ago) for the adverse performance impact of "unnecessary" curly braces.
In that light, I'd like to revisit this issue.
Briefly, I was told that:
if(true)
do_something();
is more performant than
if(true)
{
do_something();
}
The reason given, as I recall, was because the compiler would introduce a branch in the assembled code in the second case which could have a cumulative effect.
Now, I can spell complier, but beyond that I know very little about how they operate, so is the above theory true? Was it ever true?

In unoptimized as well as optimized generated code, those two statements would translate exactly to the same. The braces create a new scope where nothing is declared, so nothing can be implemented differently, semantically speaking. (Unless a dumb compiler would manage an empty stack frame for this inner block ?!)

so is the above theory true?
No.
Was it ever true?
No.
Not even with the worst ancient compilers lacking clever optimization strategies I could imagine these statements would emit different assenbly code.
These would simply be emitted as a call to the do_something subroutine.

The "facts" you were given are completely madeup. There is no performance reduction at all, as people have already mentioned in the very link you gave.
There is no way for us to explain the reasoning of something that's not true.

Related

Are these allowed optimizations in C++? [duplicate]

This question already has answers here:
Why don't compilers merge redundant std::atomic writes?
(9 answers)
Can atomic loads be merged in the C++ memory model?
(2 answers)
Closed 2 years ago.
Let std::atomic<std::int64_t> num{0}; be defined somewhere accessible/visible in the code.
Is the C++ compiler allowed to replace each of the following two codes with an empty code (something that does nothing)? Similarly, are these optimizations allowed to happen at runtime?
I am just trying to get a better understanding of how things work.
num.fetch_add(1,std::memory_order_relaxed);
num.fetch_sub(1,std::memory_order_relaxed);
and
num.fetch_add(1,std::memory_order_relaxed);
std::this_thread::yield();
num.fetch_sub(1,std::memory_order_relaxed);
I think in theory yes and even yield does not help.
But in practice no not today but possible in the future.
See:
N4455 No Sane Compiler Would Optimize Atomics
P0062R1: When should compilers optimize atomics?
"Runtime optimization" may happen if modifications coalesce. I don't know if this situation may happen in practice or not. Anyway it is not much distinguishable from "no other threads manage to observe modified value before it changes back"
In fact, the optimization effect is equivalent to "no other threads manage to observe modified value before it changes back", no matter if it is compiler optimization, or runtime. Yield is not guaranteed to help, at least because it just "gives opportunity to reschedule", which an implementation might decide to ignore. And in theory there's no synchronization between yield and an atomic operation.
On the other hand what do you expect to achieve with this?

Is returning a functions value from a for-loop bad practice 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 6 years ago.
Improve this question
My colleague just had a look at my code and said, that according to "some standard" returning a functions value out of a for loop is bad practice.
The function looks something like this:
bool CentralWidget::isBitFieldFree(const QString& define, int lsb, int msb)
{
QString defineWithoutIndex = getDefineWithoutIndex(define);
for (int i = lsb; i <= msb; i++)
{
if ((registerBitMap[defineWithoutIndex] >> i) & 1)
return false; //Returning here early...
else
registerBitMap[defineWithoutIndex] |= 1 << i;
}
return true;
}
Questions:
Is there a a standard that bans this?
is this concidered bad practice?
if so: why?
There is no such standard as this in the world of c++. However in a more specific environment (such as a company), specialized standards might apply.
With that said, it's not bad practice, in general.
a) a standard that bans this?
No.
b) is this concidered bad practice?
No.
c) question is already answered.
Other than that, it lies under the scope of personal preference, and here is mine - but this obviously not a part of a real answer:
You want to return true, after you have looped over your string, so how could you do it elegantly inside the loop? With an if statement saying that if it's the last iteration, return true, at the end of the loop?
I think this puts more lines of code in your file, without any reason, and damaging severely the readability.
There is a school of thought that says that a function should have a single entry and a single exit point. That makes some static analysis of the code easier, but in C++ very likely serves no other purpose.
This kind of thinking comes mostly from C, where it can make a lot of sense to exit the function trough a single point to ensure resources eventually taken by the function are properly cleaned up on exit. Replicating this cleanup across multiple exits is considered to be brittle and hard to maintain - I agree.
In C++ however the preferred way to control your resources is through RAII or by using RAII-classes like shared pointers, string and vector. Thus the amount of code required to clean up resources on exit is often null, because it is implicitly done in the destructors of the objects in the local scope. Therefor it usually does not make any sense to enforce single-entry/single-exit unless you have a good reason to do so.
In some coding standards you could find things like 'a function should have only one exit point'. Often this was related to cleanup procedures, but in the days of smart pointers this does not apply anymore.
So, as the other answers and comments say: No, there is no such standard.
Also, I don't think it's bad practice.
Even more: I would say you don't need the 'else', because if you exit the loop/function, processing only continues in the 'else' case. Does not matter much in your case, but if you have multiple ifs, it can save you a lot of nesting.
There can be different opinion on this and people may argue it makes an "unintuitive" control flow. But there is no standard for this.
Personally I find this a better practice than having an extra variable and condition to exit the code. You want to leave the scope at this point and you do this by returning from the function. I sometimes even put code in an extra function just to be able to use the feature of leaving the scope from anywhere with a return.
This also has the advantage of creating less lines of code. And less lines of code are less opportunities to introduce a bug.

Why and when should a goto be used in C / C++? [duplicate]

This question already has answers here:
Examples of good gotos in C or C++ [closed]
(16 answers)
Closed 9 years ago.
I know lots of questions about why not use goto, why goto is bad practice, why goto was create by devil, why the fingers of those who type goto should be ripped off, etc...
And in many answers to this questions , this question, and even at wikipedia it's possible to find reasons pro / against goto.
Even Stackoverflow has a goto tag :)
But, obviously, goto is accepted as a valid command, otherwise your compiler / interpreter wouldn't know what to do with it. Even in C / C++ it's possible to use goto, and that language even has a formal, ISO specification.
So, probably, there should be some case where only by using goto it's possible to accomplish some task. Then, why and when should a goto be used in C / C++ ?
Edit:
Just to make sure:
1 - this question doesn't require debate. It should be answerable: giving one or more cases where goto is the only solution, or stating no, it's always possible to avoid a goto. Of course, I'm not the only who can decide whether it should be closed or not, but I don't think that "too broad, asks for debate, etc" are reasons to close it.
2 - There might be some cases where goto make the code cleaner, faster, etc. I don't want those. I want to know if there exists one case where goto is the only solution (no, it's not a dup of that "give good examples of goto" question)
3 - I'll accept any downvote, with a smile on my face, if the downvote is justified. But I'm pretty sure that this question has an answer and has done previous research about the subject. Downvoting simple because those 4-letters taboo word that starts with a "G" was used... sorry...
There is no circumstance under which a goto is strictly necessary: you can always avoid it if you really want to, but to do that for purely idealogical reasons is a mistake.
For example, a friend of mine wrote a wavelet transform function that had (something like) 15 nested loops. In the event of an error in those loops, he had a goto to a cleanup block just before the function's return statement. To achieve the same effect without a goto would have involved setting a flag and testing it at every loop level, which would have made his code far less readable. In these circumstances, goto was the right choice.
The latest MISRA standard now allows gotos.
A good example where gotos make sense is when you have a large routine with a lot of exits points. You can have many return statements (not good) convolute the code with 'structured programming' conditionals (also not good) or a "goto Done; which sends the program to a set of ending statements before returning.
The MISRA standard basically allows gotos for these sort of circumstances. I think 'only downward' is one of their criteria.
The only reason I use a goto is when it is for an error return condition from a function that needs some common cleanup. The target of the goto is near the end of the function and the "normal" return returns before the label.
Here is an example where only goto will work:
https://stackoverflow.com/a/245801/193848
Basically if you have multiple nested for loops, the only way to break out of all the loops from an inner loop is with a goto statement (since unlike some other languages the C break keyword doesn't support a parameter for the number of nesting levels to break out).

Why choosing for (;;){} over while(1)? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Is “for(;;)” faster than “while (TRUE)”? If not, why do people use it?
I see this
for (;;)
{
// Some code here
}
quite often. But what benefits does it offer and why just not choose while(1){}?
They produce identical code. There are a couple of reasons why you might prefer for (;;) but it is all just personal preference:
Some compilers will warn you about conditions that are always true. for(;;) will not have that problem.
for (;;) literally reads as "Just loop forever!", whereas while (true) still appears to have some kind of condition.
I say pick one and stick with it. It doesn't matter as long as you don't switch between them arbitrarily.
This is the form of the forever loop that Kernighan and Ritchie used in their book*. There is absolutely no other reason to prefer one form over the other.
* Section 3.5 on While and For loops, example number four.
The two are equivalent and will most likely result in identical machine code. Choosing one over the other is a matter of personal preference.
It does not really matter - it is just personal preference.
I like for(;;) better because I think it underlines loop forever aspect.

What is better for(;;) {} or while(true) {}? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Is “for(;;)” faster than “while (TRUE)”? If not, why do people use it?
I would like to know which infinite loop is more preferable:
for(;;) {
// Do some stuff
}
or
#define TRUE 1
while(TRUE) {
// Do some stuff
}
Is there any difference between them from the performance point of view?
What is more preferable from coding standards point of view?
From a performance point of view it doesn't matter. The compiler will optimize both into the same assembly code. From a "coding standards" point of view, for(;;) is more terse, which is nice. Although while(TRUE) is a bit clearer, for(;;) is so common that clarity in this case is not much of an issue (in fact, the ubiquity of for(;;) may make it more clear than the while version).
No difference. while (true) might look more obvious to some.
Is there any difference between them from the performance point of view?
No, none whatsoever.
I use for (; ;) but the reason is whimsical: it kind of looks like for (ever) … (and that’s kind of an established idiom in the C++ community).
It's matter of taste, but especially matter of coding conventions used. Preferably one style should be used everywhere in same project, or same rules used in picking the style when they will be mixes. Many C++ frameworks also provide forever as macro, which in my opinion should then be preferred in code using the framework. There should be no difference in generated code.
The difference between the two is not big. You usually use for when you know how many elements to traverse. You use while if instead a condition needs to be satisfied