Why choosing for (;;){} over while(1)? [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 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.

Related

Why char and other C function should not be used in C++? [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 1 year ago.
Improve this question
Can someone please enlighten me regarding answers in this question Assigning a value to char* in a struct?
In the answers, they told the asker not to mix C and C++, i.e. use string and cin if it's C++
or
char if it's C. It makes me confuse since what I know is that we can use like char, printf and so on in C++ by including appropriate libraries. What if we should work with char in C++ project because of several reasons?
One of the answer also tells that typedef struct{...}x; is not necessary in C++, while so far I know now it is used to prevent re-typing struct x, e.g x Name1; x Name2; instead of struct x Name1; struct x Name2;. It is confusing enough for a beginner like me.
C and C++ are different languages, no matter how similar they look and what common subset they have. Being different languages, they have methods that work only within that language. Mixing them is fine when you know what you are doing. As the other answer states, char arrays are more difficult to use than std::string, although they have their advantages. For a beginner, if you want to learn C++, learning std::string will save you quite a lot of debugging strange things happening in your code compared to using char*
The reason why you don't need typedef struct {} X is a prime specimen of C and C++ being different languages. You will not need to repeat struct X every time you use in C++, with or without typedef. I'd even say it's harmful, because void foo(struct X*) does something more than just void foo(X*). Moreover, struct in C++ is equivalent to class, the only difference is the default access specifier (struct has public as default, class has private).
zero terminated char * strings have been the source of an enormous number of bugs, crashes and security flaws over the years, usually because someone forgets to zero terminate them, or because they forget a 4 character string needs to be 5 characters long, or a number of other scenarios.
They CAN be used safely, but experience tells us we will make mistakes, and waste time and effort testing and checking and testing again, when we could just use a string class, that contains all the checks in one place, is tested in one place, and never needs to be worried about again. So why on earth wouldn't we?
What if we should work with char in C++ project because of several reasons?
There is nothing stopping you :D
That said, the design of std::cin and std::string is the way it is, because working with char* and scanf is error prone and inefficient (and they were added to the C++ standard library to provide better ways).
There are reasons to work directly with char* in C++, but most of them are really bad reasons (a good reason would be to learn - for example).
The C++ compiler doesn't care if you mix C style code with C++ style code, it will produce some result.
Other humans care if you mix C style code with C++ style code, because it's really easy for it to do something subtly different from what you think it should.
C++ is not a safe language, where you simply can't do wrong things, nor is it a safer language, which will loudly tell you when you do wrong things. It is an unsafe language, where if you do things wrong, you might not notice right up until the worst possible moment.
This is an opinion-based question (which I suppose is why it's been downvoted), so I'm going to wade in here with a dissenting opinion:
Why char and other C function should not be used in C++?
Well, it's partly because some people have rigid opinions on what programming should be, and they like to try to force these opinions on you. :-)
It's true that C has many unsafe aspects, particularly by modern standards. It's true that C++ has "better" or at least different ways of dealing with several things, including strings, I/O, and memory allocation.
But at the end of the day, programming languages are tools, and using them appropriately is always a balance between using them as designed, and getting your job done.
C++ was designed to be a superset of C. (These days it's not, of course, but the intent is still clearly there.) So there's nothing inherently wrong with using C features or idioms in a C++ program -- the whole point of Bjarne Stroustrup's exercise was always to allow you to.
If you choose to use a C feature in a C++ program, it might be an ignorant or a bad or a dangerous thing to do, or it might be expedient and decently appropriate thing to do. At the end of the day, it depends on whether it gets the job done, whether it's maintainable, and whether it's acceptable to any other people you may be sharing code or collaborating with.
For example, I code in both C and C++. And while I understand how cout and << are a "better" way of doing output than C's printf, I confess that I still use printf in C++ programs a lot of the time, because it's so much more convenient. Despite its notorious and insurmountable warts and problems, printf has always been one of my favorite parts of C, and I am loath to give it up.
I'm not saying you should use printf in C++, or that you should ignore all the various benefits of std::string, and new/delete, and the STL. "When in Rome, do as the Romans do" is a fine philosophy, and most of the time, you should use C++ idioms in C++. But if you have a good reason to fall back on a C idiom once in a while, I don't believe there's any shame in that, and I don't believe you should let anyone guilt-trip you into abandoning it just because they think it's "not proper".
[It will be interesting to see how violently this answer gets downvoted for its heretical advice. :-) ]

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.

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).

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