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

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

Related

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

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.

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.

Is it a good idea to apply some basic macros to simplify code in a large project?

I've been working on a foundational c++ library for some time now, and there are a variety of ideas I've had that could really simplify the code writing and managing process. One of these is the concept of introducing some macros to help simplify statements that appear very often, but are a bit more complicated than should be necessary.
For example, I've come up with this basic macro to simplify the most common type of for loop:
#define loop(v,n) for(unsigned long v=0; v<n; ++v)
This would enable you to replace those clunky for loops you see so much of:
for (int i = 0; i < max_things; i++)
With something much easier to write, and even slightly more efficient:
loop (i, max_things)
Is it a good idea to use conventions like this? Are there any problems you might run into with different types of compilers? Would it just be too confusing for someone unfamiliar with the macro(s)?
IMHO this is generally a bad idea. You are essentially changing well known and understood syntax to something of your own invention. Before long you may find that you have re-invented the language. :)
No, not a good idea.
int max = 23;
loop(i, ++max)...
It is, however, a good idea to refactor commonly used code into reusable components and then reuse instead of copy. You should do this through writing functions similar to the standard algorithms like std::find(). For instance:
template < typename Function >
void loop(size_t count, Function f)
{
for (size_t i = 0; i < count, ++i) f();
}
This is a much safer approach:
int max = 23;
loop(++max, boost::bind(....));
I think you've provided one strong argument against this macro with your example usage. You changed the loop iterator type from int to unsigned long. That has nothing to do with how much typing you want to do, so why change it?
That cumbersome for loop specifies the start value, end value, type and name of the iterator. Even if we assume the final part will always be ++name, and we're happy to stick to that, you have two choices - remove some of the flexibility or type it all out every time. You've opted to remove flexibility, but you also seem to be using that flexibility in your code base.
I would say it depends upon whether you expect anyone else to ever have to make sense of your code. If it's only ever going to be you in there, then I don't see a problem with the macros.
If anyone else is ever going to have to look at this code, then the macros are going to cause problems. The other person won't know what they are or what they do (no matter how readable and obvious they seem to you) and will have to go hunting for them when they first run across them. The result will be to make your code unreadable to anyone but yourself - anyone using it will essentially have to learn a new language and program at the same time.
And since the chances of it just being you dealing with the code are pretty much nil if you hope the code to be a library that will be for more than just your personal use - then I'd go with don't.
In Unix, I find that by the time I want to create an alias for a command I use all the time, the command is on my fingers, and I'd have a harder time remembering the syntax of my alias than the original command.
The same applies here -- by the time you use an idiom so much that you want to create a macro for it, the idiom will be on you fingers and cause you more pain than just typing out the code.
Getting rid of the for loops is generally a good idea -- but replacing them with macros is not. I'd take a long, hard look at the standard library algorithms instead.
Apart from the maintenance/comprehension problems mentionned by others, you'll also have a hard time breaking and single-stepping through macro code.
One area where I think macros might be acceptable would be for populating large data structures with constants/litterals (when it can save an excessive amount of typing). You normally would not single-step through such code.
Steve Jessop makes a good point. Macros have their uses. If I may expound upon his statements, I would go so far as to say that the argument for or against macros comes down to "It depends". If you make your macros without careful thought, you risk making future maintaners' lives harder. On the other hand, using the wxWidgets library requires using library provided macros to connect your code with the gui library. In this case, the macros lower the barrier of entry for using the library, as magic whose innards are irrelevant to understanding how to work with the library are hidden away from the user. In this case, the user is saved from having to understand things they really don't need to know about, and can be argued that this is a "Good" use of macros. Also, wxWidgets clearly documents how these macros are supposed to be used. So make sure that what you hide isn't something that is going to need to be understood by someone else coming in.
Or, if its just for your use, knock yourself out.
It's a question of where you're getting your value. Is typing those 15 extra characters in your loops really what's slowing your development down? Probably not. If you've got multiple lines of confusing, unavoidable boilerplate popping up all over the place, then you can and should look for ways to avoid repeating yourself, such as creating useful functions, cleaning up your class hierarchies, or using templates.
But the same optimization rules apply to writing code as to running it: optimizing small things with little effect is not really a good use of time or energy.

Guidelines to improve your code

Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
What guidelines do you follow to improve the general quality of your code? Many people have rules about how to write C++ code that (supposedly) make it harder to make mistakes. I've seen people insist that every if statement is followed by a brace block ({...}).
I'm interested in what guidelines other people follow, and the reasons behind them. I'm also interested in guidelines that you think are rubbish, but are commonly held. Can anyone suggest a few?
To get the ball rolling, I'll mention a few to start with:
Always use braces after every if / else statement (mentioned above). The rationale behind this is that it's not always easy to tell if a single statement is actually one statement, or a preprocessor macro that expands to more than one statement, so this code would break:
// top of file:
#define statement doSomething(); doSomethingElse
// in implementation:
if (somecondition)
doSomething();
but if you use braces then it will work as expected.
Use preprocessor macros for conditional compilation ONLY. preprocessor macros can cause all sorts of hell, since they don't allow C++ scoping rules. I've run aground many times due to preprocessor macros with common names in header files. If you're not careful you can cause all sorts of havoc!
Now over to you.
A few of my personal favorites:
Strive to write code that is const correct. You will enlist the compiler to help weed out easy to fix but sometimes painful bugs. Your code will also tell a story of what you had in mind at the time you wrote it -- valuable for newcomers or maintainers once you're gone.
Get out of the memory management business. Learn to use smart pointers: std::auto_ptr, std::tr1::shared_ptr (or boost::shared_ptr) and boost::scoped_ptr. Learn the differences between them and when to use one vs. another.
You're probably going to be using the Standard Template Library. Read the Josuttis book. Don't just stop after the first few chapters on containers thinking that you know the STL. Push through to the good stuff: algorithms and function objects.
Delete unnecessary code.
That is all.
Use and enforce a common coding style and guidelines. Rationale: Every developer on the team or in the firm is able to read the code without distractions that may occur due to different brace styles or similar.
Regularly do a full rebuild of your entire source base (i.e. do daily builds or builds after each checkin) and report any errors! Rationale: The source is almost always in a usable state, and problems are detected shortly after they are "implemented", where problem solving is cheap.
Turn on all the warnings you can stand in your compiler (gcc: -Wall is a good start but doesn't include everything so check the docs), and make them errors so you have to fix them (gcc: -Werror).
Google's style guide, mentioned in one of these answers, is pretty solid. There's some pointless stuff in it, but it's more good than bad.
Sutter and Alexandrescu wrote a decent book on this subject, called C++ Coding Standards.
Here's some general tips from lil' ole me:
Your indentation and bracketing style are both wrong. So are everyone else's. So follow the project's standards for this. Swallow your pride and setup your editor so that everything is as consistent as possible with the rest of the codebase. It's really really annoying having to read code that's indented inconsistently. That said, bracketing and indenting have nothing whatsoever to do with "improving your code." It's more about improving your ability to work with others.
Comment well. This is extremely subjective, but in general it's always good to write comments about why code works the way it does, rather than explaining what it does. Of course for complex code it's also good for programmers who may not be familiar with the algorithm or code to have an idea of what it's doing as well. Links to descriptions of the algorithms employed are very welcome.
Express logic in as straightforward a manner as possible. Ironically suggestions like "put constants on the left side of comparisons" have gone wrong here, I think. They're very popular, but for English speakers, they often break the logical flow of the program to those reading. If you can't trust yourself (or your compiler) to write equality compares correctly, then by all means use tricks like this. But you're sacrificing clarity when you do it. Also falling under this category are things like ... "Does my logic have 3 levels of indentation? Could it be simpler?" and rolling similar code into functions. Maybe even splitting up functions. It takes experience to write code that elegantly expresses the underlying logic, but it's worth working at it.
Those were pretty general. For specific tips I can't do a much better job than Sutter and Alexandrescu.
In if statements put the constant on the left i.e.
if( 12 == var )
not
if( var == 12 )
Beacause if you miss typing a '=' then it becomes assignment. In the top version the compiler says this isn't possible, in the latter it runs and the if is always true.
I use braces for if's whenever they are not on the same line.
if( a == b ) something();
if( b == d )
{
bigLongStringOfStuffThatWontFitOnASingleLineNeatly();
}
Open and close braces always get their own lines. But that is of course personal convention.
Only comment when it's only necessary to explain what the code is doing, where reading the code couldn't tell you the same.
Don't comment out code that you aren't using any more. If you want to recover old code, use your source control system. Commenting out code just makes things look messy, and makes your comments that actually are important fade into the background mess of commented code.
Use consistent formatting.
When working on legacy code employ the existing style of formatting, esp. brace style.
Get a copy of Scott Meyer's book Effective C++
Get a copy of Steve MConnell's book Code Complete.
There is also a nice C++ Style Guide used internally by Google, which includes most of the rules mentioned here.
Start to write a lot of comments -- but use that as an opportunity to refactor the code so that it's self explanatory.
ie:
for(int i=0; i<=arr.length; i++) {
arr[i].conf() //confirm that every username doesn't contain invalid characters
}
Should've been something more like
for(int i=0; i<=activeusers.length; i++) {
activeusers[i].UsernameStripInvalidChars()
}
Use tabs for indentations, but align data with spaces
This means people can decide how much to indent by changing the tab size, but also that things stay aligned (eg you might want all the '=' in a vertical line when assign values to a struct)
Allways use constants or inline functions instead of macros where posible
Never use 'using' in header files, because everything that includes that heafer will also be affected, even if the person includeing your header doesn't want all of std (for example) in their global namespace.
If something is longer than about 80 columes, break it up into multiple lines eg
if(SomeVeryLongVaribleName != LongFunction(AnotherVarible, AString) &&
BigVaribleIsValid(SomeVeryLongVaribleName))
{
DoSomething();
}
Only overload operators to make them do what the user expects, eg overloading the + and - operators for a 2dVector is fine
Always comment your code, even if its just to say what the next block is doing (eg "delete all textures that are not needed for this level"). Someone may need to work with it later, posibly after you have left and they don't want to find 1000's of lines of code with no comments to indicate whats doing what.
setup coding convention and make everyone involved follow the convention (you wouldn't want reading code that require you to figure out where is the next statement/expression because it is not indented properly)
constantly refactoring your code (get a copy of Refactoring, by Martin Fowler, pros and cons are detailed in the book)
write loosely coupled code (avoid writing comment by writing self-explanatory code, loosely coupled code tends to be easier to manage/adapt to change)
if possible, unit test your code (or if you are macho enough, TDD.)
release early, release often
avoid premature optimization (profiling helps in optimizing)
In a similar vein you might find some useful suggestions here: How do you make wrong code look wrong? What patterns do you use to avoid semantic errors?
Where you can, use pre-increment instead of post-increment.
I use PC-Lint on my C++ projects and especially like how it references existing publications such as the MISRA guidelines or Scott Meyers' "Effective C++" and "More Effective C++". Even if you are planning on writing very detailed justifications for each rule your static analysis tool checks, it is a good idea to point to established publications that your user trusts.
Here is the most important piece of advice I was given by a C++ guru, and it helped me in a few critical occasions to find bugs in my code:
Use const methods when a method is not supposed to modify the object.
Use const references and pointers in parameters when the object is not supposed to modify the object.
With these 2 rules, the compiler will tell you for free where in your code the logic is flawed!
Also, for some good techniques you might follow Google's blog "Testing on the Toilet".
Look at it six months later
make sure you indent properly
Hmm - I probably should have been a bit more specific.
I'm not so much looking for advice for myself - I'm writing a static code analysis tool (the current commercial offerings just aren't good enough for what I want), and I'm looking for ideas for plugins to highlight possible errors in the code.
Several people have mentioned things like const correctness and using smart pointers - that's the kind of think I can check for. Checking for indentation and commenting is a bit harder to do (from a programming point of view anyway).
Smart pointers have a nice way of indicating ownership very clearly. If you're a class or a function:
if you get a raw pointer, you don't own anything. You're allowed to use the pointee, courtesy of your caller, who guarantees that the pointee will stay alive longer than you.
if you get a weak_ptr, you don't own the pointee, and on top of that the pointee can disappear at any time.
if you get a shared_ptr, you own the object along with others, so you don't need to worry. Less stress, but also less control.
if you get an auto_ptr, you are the sole owner of the object. It's yours, you're the king. You have the power to destroy that object, or give it to someone else (thereby losing ownership).
I find the case for auto_ptr particularly strong: in a design, if I see an auto_ptr, I immediately know that that object is going to "wander" from one part of the system to the other.
This is at least the logic I use on my pet project. I'm not sure how many variations there can be on the topic, but until now this ruleset has served me well.