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 am not sure wether I should post this here or not, but I just had a debate about C++ good practises with a coworker today and I can't find the point we were discussing in the CppCoreGuidelines or any forums.
We were talking about "if" "else if" "else" statement, and my coworker was saying that if you have a "if - else if" statement then you must put a "else", even if it is empty.
For example, in his opinion, things like this is no good practise.
if (condition1)
{
// Some instructions to do when condition1
...
}
else if (condition2)
{
// Some instructions to do when condition2
...
}
and I should rather write this code :
if (condition1)
{
// Some instructions to do when condition1
...
}
else if (condition2)
{
// Some instructions to do when condition2
...
}
else
{
/* Do nothing */
}
His main point was that just like switch statements must have a default case, if - else if statements must have a else.
I have several questions :
is that true ?
if yes, why ? (I don't understand the problem).
why would some guidelines want to force that ?
This is all very personal.
is that true ?
From a language legality perspective, no that's false.
Some guidelines might want programmers to explicitly add else statements but personally this sounds like an anti-pattern to me.
my coworker was saying that if you have a "if - else if" statement then you must put a "else", even if it is empty.
No style guide I have ever come across says that. And, if there is one, it's just a matter of opinion.
I do sometimes write "empty" else blocks, but only when they contain some interesting, useful, explanatory documenting comment about why nothing's happening in the else case when it might at first glance appear like a natural thing to do.
if (FozzieBearIsAlive())
{
GiveMissPiggyATreat();
}
else
{
// Miss Piggy doesn't deserve a treat, because she may
// have killed Fozzie Bear
}
It's a pretty contrived example, which could otherwise be written like this:
// Give Miss Piggy a treat, but only if Fozzie Bear is alive
// because otherwise we might wonder whether she killed him
if (FozzieBearIsAlive())
{
GiveMissPiggyATreat();
}
But sometimes the former is nicer.
Mandating that you always include some empty else block with nothing in it, though, is something I have not heard of and would not support.
His main point was that just like switch statements must have a default case
Also false, except in the sense of some subjective style guide.
In fact, when switching on enums, I discourage default cases unless you functionally require one, because you prevent the compiler from warning you when you add an enumeration and forget to update all your switches.
First of all, switch statements do not require a default case. In fact, they may be completely empty:
switch (...) {
// fine
}
Similarly, if does not require an else.
Some guidelines have strange rules, and some may indeed require to always have all possible branches explicitly written down in the code. However, it is very rare to do so, specially with branches.
I have personally seen very weird requirements out there on contracted code, so I can believe some guidelines/certification/contract/... may force it, specially older ones. My guess is that they want to be "formal" or maybe they hope it helps with "code quality" or with formal verification (if done manually, for some reason...).
It really comes down to the coding guidelines of whatever project/company you're working for. Beyond that, it's personal preference.
For example, my current company likes to always ensure there's a default case for switch statements and to add the else clause for if statements.
Just pay attention to your company/project's guidelines and you'll be good.
Related
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 1 year ago.
Improve this question
Let suppose the following example:
int main()
{
int value=1;
switch( value )
{
case 1:
{
return 0;
} break;
default:
{
}
}
}
Returning from a switch case is not structured programming, but early exit is considered by most developers as an acceptable deviation (wiki reference)
Most modern compilers will complain about this code because:
9: 'break' will never be executed
However, removing the break sentence will trigger the question: "Is this a fallthrough? if yes, why is the [[fallthrough]] attribute not specified?"
The obvious solution would be an hypothetical [[no_fallthrough]], but I found nothing in that direction.
My question is:
What is the appropriate approach in this case?
Should return inside switch be avoided?
Should break be kept with the warning?
Should break be removed and a comment indicating the //[[no_fallthrough]]?
Should break be removed and the developer notice that the return statement is incompatible with break, and cross-finger that no refactoring will break this.
However, removing the break sentence will trigger the question: "Is this a fallthrough?
The answer to the triggered question is: No, it does not fall through because it returns out of the function and thus out of the block that is inside the function.
Should return inside switch be avoided?
If you care about strict structured programming, then yes.
But as you quoted, most people consider it acceptable.
Should break be kept with the warning?
I recommend against control structures that have no effect, unless there is a good argument for using it. I see no good argument for having it here.
Should break be removed
I recommend this. A developer should be aware that return does not fall through as much as break, continue (if switch is inside loop), throw and goto don't.
and cross-finger that no refactoring will break this.
In case of implicit fallthrough I recommend using the standard attribute [[fallthrough]] if you use C++17 at least so that you don't have to rely on crossed fingers alone.
Otherwise use a warning is better than nothing.
Perhaps more interesting case is call to a [[noreturn]] function:
// in some header
[[noreturn]] void fun();
case N:
fun();
// no fall through
I recommend at least commenting as shown, since familiarity with every function cannot be assumed. Functions don't tend to flip between noreturn and non-noreturn, but if that happens, implicit fallthough warning covers this case too.
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 know that the current C++ standard special cases main so that falling off the end has the same effect as return 0; rather than undefined behavior.
I was recently surprised to see an example at codereview where the responses not only pointed out that including the final return 0; is optional, but actually went so far as to remove it from the original code.
Thus prompts my question — is it really considered bad style to make the return 0; explicit at the end of main? What is the rationale for or against?
I'll take a wild stab in the dark here and say that people fall into two camps:
those who remove the line think it is redundant and all such code should be
removed for brevity
those who add the line think it makes the return value clear and unambiguous to lesser coders.
Personally, I would tend to always write a meaningful return statement in main in my production code (if only because my production mains tend to also contain code paths that end up returning something other than 0, generally in exception handlers), although I wouldn't bother for a trivial main that never returns anything else; for example, I don't think I've ever done so in, say, a Coliru post for a Stack Overflow demonstration.
Some would say that it's absurd to alter a codebase to flip between these two states, that the arguments are both very weak in the grand scheme of things, and that such a personal choice is not worth risking the introduction of bugs.
But I'd say this depends almost entirely on what your environment is like. If you're halfway through a release cycle, of course you're going to make code maintenance improvements and style adjustments: this is the best time to avoid accruing technical debt, and you absolutely want to do that. But if you're planning to make this change directly on a production server, or in version control one week before that big release, you're out of your mind.
(Hopefully your policies prevent such madness anyway. Code freeze, yes? No changes to production, right?)
So, although it goes without saying that the underlying choice is highly subjective, we can quantify the risk/benefit of enforcing such a choice after-the-fact.
But never mind real life, what about on Code Review? Well, I have no idea; you'd have to ask them. Personally, on those specific examples, I probably would have removed it too, albeit with the written caveat that this were purely a style choice. Whether purely style changes are appropriate on Code Review is a question for Code Review Meta.
From C++, 3.6.1 Main Function
(3.6.1/5) An implementation shall not predefine the main function. This
function shall not be overloaded. It shall have a return type of type
int, but otherwise its type is implementation-defined. All
implementations shall allow both of the following definitions of main:
int main() { /* ... */ } and
int main(int argc, char* argv[]) { /* ... */ }
So in C++, two prominent signatures for main function are : int main() and int main(int argc, char** argv)
Further in C++, 3.6.1 Main function
(3.6.1/5) A return statement in main has the effect of leaving the
main function (destroying any objects with automatic storage duration)
and calling exit with the return value as the argument. If control
reaches the end of main without encountering a return statement, the
effect is that of executing return 0;
So, although the signature suggest that function should return some integer, it is not necessary to return 0. By default, C++ considers return value to be 0.
Advantages:
- Treating main as normal function and following similar C++ coding convention
- return 0 explicitly specify normal return value, in other cases we can return non-zero value
Although, all these points are matter of coding convention. It is still choice of programmer!
This might be a silly question, but I'm new to C++ and programming in general and I couldn't find the answer on here. I know in C++, the { } are optional in some cases. For example, if you have a simple if statement where only one operation is performed, you don't need to surround it with { }.
I was just wondering if the extra brackets have any effect (even the smallest) on the speed of the program. The reason I ask is because I always include the curly brackets in all of my statements even if not required, just because I like to block out my code.
My personal preference is:
if (foo)
{
bar;
}
Instead of simply
if (foo)
bar;
I just like the way it looks when reading the code. But, if this actually has an effect on the speed of the code, it's probably not a good idea. Does anyone know if extra brackets affects the speed? Thanks.
No it does not.
In general, due to the "as if"-rule, the compiler has a lot of leeway to optimize things.
Still, it is a style issue, and there are seldom straight answers everyone agrees on.
There are people who only use braces of any kind if they either significantly clarify the code or are neccessary, and those who always use a code block for conditionals and loops.
If you work in a team/on contract/on an inherited codebase, try to conform to their style, even if it's not yours.
It has the same result for the compiler. It's like initialize a variable like these:
int a = 0;
int a {0};
int a (0);
The have the same result as well. It's a matter of style.
The curly braces are there to help the compiler figure out the scope of a variable, condition, function declaration, etc. It doesn't affect the runtime performance once the code is compiled into an executable. Braces make the code more maintainable
It helps to debug the code with less pain, imagine below code snippet and you need to evaluate the do_some_operation by putting breakpoint. The second option will serve the purpose better
if( some_condition ) { do_some_operation; }
--------------------------
if( some_condition )
{
do_some_operation;
}
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 7 years ago.
Improve this question
In a recent code review, a contributor is trying to enforce that all NULL checks on pointers be performed in the following manner:
int * some_ptr;
// ...
if (some_ptr == NULL)
{
// Handle null-pointer error
}
else
{
// Proceed
}
instead of
int * some_ptr;
// ...
if (some_ptr)
{
// Proceed
}
else
{
// Handle null-pointer error
}
I agree that his way is a little more clear in the sense that it's explicitly saying "Make sure this pointer is not NULL", but I would counter that by saying that anyone who's working on this code would understand that using a pointer variable in an if statement is implicitly checking for NULL. Also I feel the second method has a smaller chance of introducing a bug of the ilk:
if (some_ptr = NULL)
which is just an absolute pain to find and debug.
Which way do you prefer and why?
In my experience, tests of the form if (ptr) or if (!ptr) are preferred. They do not depend on the definition of the symbol NULL. They do not expose the opportunity for the accidental assignment. And they are clear and succinct.
Edit: As SoapBox points out in a comment, they are compatible with C++ classes such as unique_ptr, shared_ptr, auto_ptr that are objects that act as pointers and which provide a conversion to bool to enable exactly this idiom. For these objects, an explicit comparison to NULL would have to invoke a conversion to pointer which may have other semantic side effects or be more expensive than the simple existence check that the bool conversion implies.
I have a preference for code that says what it means without unneeded text. if (ptr != NULL) has the same meaning as if (ptr) but at the cost of redundant specificity. The next logical thing is to write if ((ptr != NULL) == TRUE) and that way lies madness. The C language is clear that a boolean tested by if, while or the like has a specific meaning of non-zero value is true and zero is false. Redundancy does not make it clearer.
if (foo) is clear enough. Use it.
I'll start off with this: consistency is king, the decision is less important than the consistency in your code base.
In C++
NULL is defined as 0 or 0L in C++.
If you've read The C++ Programming Language Bjarne Stroustrup suggests using 0 explicitly to avoid the NULL macro when doing assignment, I'm not sure if he did the same with comparisons, it's been a while since I read the book, I think he just did if(some_ptr) without an explicit comparison but I am fuzzy on that.
The reason for this is that the NULL macro is deceptive (as nearly all macros are) it is actually 0 literal, not a unique type as the name suggests it might be. Avoiding macros is one of the general guidelines in C++. On the other hand, 0 looks like an integer and it is not when compared to or assigned to pointers. Personally I could go either way, but typically I skip the explicit comparison (though some people dislike this which is probably why you have a contributor suggesting a change anyway).
Regardless of personal feelings this is largely a choice of least evil as there isn't one right method.
This is clear and a common idiom and I prefer it, there is no chance of accidentally assigning a value during the comparison and it reads clearly:
if (some_ptr) {}
This is clear if you know that some_ptr is a pointer type, but it may also look like an integer comparison:
if (some_ptr != 0) {}
This is clear-ish, in common cases it makes sense... But it's a leaky abstraction, NULL is actually 0 literal and could end up being misused easily:
if (some_ptr != NULL) {}
C++11 has nullptr which is now the preferred method as it is explicit and accurate, just be careful about accidental assignment:
if (some_ptr != nullptr) {}
Until you are able to migrate to C++0x I would argue it's a waste of time worrying about which of these methods you use, they are all insufficient which is why nullptr was invented (along with generic programming issues which came up with perfect forwarding.) The most important thing is to maintain consistency.
In C
C is a different beast.
In C NULL can be defined as 0 or as ((void *)0), C99 allows for implementation defined null pointer constants. So it actually comes down to the implementation's definition of NULL and you will have to inspect it in your standard library.
Macros are very common and in general they are used a lot to make up for deficiencies in generic programming support in the language and other things as well. The language is much simpler and reliance on the preprocessor more common.
From this perspective I'd probably recommend using the NULL macro definition in C.
I use if (ptr), but this is completely not worth arguing about.
I like my way because it's concise, though others say == NULL makes it easier to read and more explicit. I see where they're coming from, I just disagree the extra stuff makes it any easier. (I hate the macro, so I'm biased.) Up to you.
I disagree with your argument. If you're not getting warnings for assignments in a conditional, you need to turn your warning levels up. Simple as that. (And for the love of all that is good, don't switch them around.)
Note in C++0x, we can do if (ptr == nullptr), which to me does read nicer. (Again, I hate the macro. But nullptr is nice.) I still do if (ptr), though, just because it's what I'm used to.
Frankly, I don't see why it matters. Either one is quite clear and anyone moderately experienced with C or C++ should understand both. One comment, though:
If you plan to recognize the error and not continue executing the function (i.e., you are going to throw an exception or return an error code immediately), you should make it a guard clause:
int f(void* p)
{
if (!p) { return -1; }
// p is not null
return 0;
}
This way, you avoid "arrow code."
Personally I've always used if (ptr == NULL) because it makes my intent explicit, but at this point it's just a habit.
Using = in place of == will be caught by any competent compiler with the correct warning settings.
The important point is to pick a consistent style for your group and stick to it. No matter which way you go, you'll eventually get used to it, and the loss of friction when working in other people's code will be welcome.
Just one more point in favor of the foo == NULL practice:
If foo is, say, an int * or a bool *, then the if (foo) check can accidentally be interpreted by a reader as testing the value of the pointee, i.e. as if (*foo). The NULL comparison here is a reminder that we're talking about a pointer.
But I suppose a good naming convention makes this argument moot.
The C Programming Language (K&R) would have you check for null == ptr to avoid an accidental assignment.
Actually, I use both variants.
There are situations, where you first check for the validity of a pointer, and if it is NULL, you just return/exit out of a function. (I know this can lead to the discussion "should a function have only one exit point")
Most of the time, you check the pointer, then do what you want and then resolve the error case. The result can be the ugly x-times indented code with multiple if's.
If style and format are going to be part of your reviews, there should be an agreed upon style guide to measure against. If there is one, do what the style guide says. If there's not one, details like this should be left as they are written. It's a waste of time and energy, and distracts from what code reviews really ought to be uncovering. Seriously, without a style guide I would push to NOT change code like this as a matter of principle, even when it doesn't use the convention I prefer.
And not that it matters, but my personal preference is if (ptr). The meaning is more immediately obvious to me than even if (ptr == NULL).
Maybe he's trying to say that it's better to handle error conditions before the happy path? In that case I still don't agree with the reviewer. I don't know that there's an accepted convention for this, but in my opinion the most "normal" condition ought to come first in any if statement. That way I've got less digging to do to figure out what the function is all about and how it works.
The exception to this is if the error causes me to bail from the function, or I can recover from it before moving on. In those cases, I do handle the error first:
if (error_condition)
bail_or_fix();
return if not fixed;
// If I'm still here, I'm on the happy path
By dealing with the unusual condition up front, I can take care of it and then forget about it. But if I can't get back on the happy path by handling it up front, then it should be handled after the main case because it makes the code more understandable. In my opinion.
But if it's not in a style guide then it's just my opinion, and your opinion is just as valid. Either standardize or don't. Don't let a reviewer pseudo-standardize just because he's got an opinion.
This is one of the fundamentals of both languages that pointers evaluate to a type and value that can be used as a control expression, bool in C++ and int in C. Just use it.
I'm a huge fan of the fact that C/C++ doesn't check types in the boolean conditions in if, for and while statements. I always use the following:
if (ptr)
if (!ptr)
even on integers or other type that converts to bool:
while(i--)
{
// Something to do i times
}
while(cin >> a >> b)
{
// Do something while you've input
}
Coding in this style is more readable and clearer to me. Just my personal opinion.
Recently, while working on OKI 431 microcontroller, I've noticed that the following:
unsigned char chx;
if (chx) // ...
is more efficient than
if (chx == 1) // ...
because in later case the compiler has to compare the value of chx to 1. Where chx is just a true/false flag.
Pointers are not booleans
Modern C/C++ compilers emit a warning when you write if (foo = bar) by accident.
Therefore I prefer
if (foo == NULL)
{
// null case
}
else
{
// non null case
}
or
if (foo != NULL)
{
// non null case
}
else
{
// null case
}
However, if I were writing a set of style guidelines I would not be putting things like this in it, I would be putting things like:
Make sure you do a null check on the pointer.
Most compilers I've used will at least warn on the if assignment without further syntax sugar, so I don't buy that argument. That said, I've used both professionally and have no preference for either. The == NULL is definitely clearer though in my opinion.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 13 years ago.
I was recently involved in an argument with a coworker involving one line if statements and wanted to see what stackoverflow thought.
Do you feel that the statement should be written as:
if(condition)
{
statement = new assignment;
}
OR
if(condition)
statement=new assignment;
please provide a good reason for your decision.
if you should really use one line if
if(condition) statement=new assignment;
will be better since its one line, it should contain one operation.
I always use enclosing braces to reduce the risk that someone (including myself) will later introduce a bug by editing the code around the if statement without paying careful attention to which line(s) belong as part of the if-condition.
EDIT:
Here's a live example if this I just happened to come across in some old code:
if (form.validateUpload (messages, this))
return getErrorOutcome (ctx, messages);
if (LOG.isInfoEnabled ())
LOG.info ("CREATING UPLOAD");
Notice how both "if" statements are in the main block of code but due to poor formatting, at first glance they appear to be nested. Sure any "good" programmer should quickly see what's happening, but why cause any unnecessary confusion?
I've always been a fan of braces. If someone were to modify a oneline if statement like so:
if(condition) statement=new assignment;
to
if(condition)
statement = new assignment;
another statement;
You won't get the expected behavior.
Using the braces pretty much insures that if someone modifies an if statement, they'll make sure to put the right statements in the right place.
This really depends on the coding style of your group. The group should have consistent coding standards. For my current group we always use:
if (condition) {
statement = new assignment;
}
We do this to prevent mistakes caused by forgetting the braces after the if statement, such as:
if (condition)
statement1;
statement2;
//statement2 is not part of the if statement, but it looks like it because of wrong indentation
Another group that I worked with until just recently always used this syntax for one-line if statements:
if (condition)
statement1;
Personally I don't like this as much because it's less explicit; but the most important thing is to stick to a consistent coding standard for your group or project, so that code you write looks like code your co-workers write, and is just as easy to read for everyone in the group.
The conventions of your IDE or environment can provide a good basis for your coding standards, and may even be tailored to your group's style.
I always do one-line if statements sans-brackets. The presence of brackets indicates (syntactically correctly) that "oh, I can do something else in here..." and I don't like the temptation. Anything that involves more than one statement should be broken up into multiple lines with proper brackets.
if(condition)
statement=new assignment;
or
if(condition) statement=new assignment;
if (condition)
{
statement = new assignment;
}
is what I would write. Namely because I like tidy code which saves time to read/edit/understand.
In very few cases I'd make an exception normally only when I'm quick and dirty coding something for debugging etc.
A one line if statement is always very easily corrupted by how the semicolon is placed.
I would go without the brackets.
The only reason you would need the brackets is if you had multiple statements inside the block.
Sounds like a waste of an argument though.
As a rule, I abhor one-line ifs except in this Perl case
operation if condition;
I have auto-format setup to kill your one-liner, which puts it on two lines. As such, it needs braces.
I always use enclosing brackets and I never code one line ifs, my approach looks like this
if(condition) {
statement = new assignment;
}
because I code Java and that's the convention for the language. Check:
http://java.sun.com/docs/codeconv/html/CodeConventions.doc6.html#449
Note: if statements always use braces
{}. Avoid the following error-prone
form:
if (condition) //AVOID! THIS OMITS THE BRACES {}!
statement;
The use of brackets prevent bugs: some else could add later new sentences that are suposed to be executed if the condition and forgetting the brackets