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
Related
Is there way to get rid or find by linting (or maybe seding/regexping) these nasty situations when your have just one line of code after if/for statement, without curly braces? Like this one:
if(condition)
return;
For reference why would I want to get rid of that - there are lots of reasons given in this thread:
What's the purpose of using braces (i.e. {}) for a single-line if or loop?
I maintain some legacy code, and deal with some not-really-finished code from other people, and from time to time stumble on situation when this code-style works like a trip wire when debugging:
if(condition_for_early_return)
LOG("Im here") // surprise surprise, I just broke control logic
return;
Also, I've seen code like that:
if(condition)
<tabs> do_smth();
<spaces> do_smth_else();
Of course if contains only first do_smth(), compiler is not confused. But because the do_ functions are visually aligned, I wonder - is this intended behaviour or is it a bug that was never found in this legacy code.
I know cppcheck does not catch these situation - already tried that.
Do you have any way of finding these traps automatically?
GCC has:
-Wmisleading-indentation (C and C++ only)
Warn when the indentation of the code does not reflect the block
structure. Specifically, a warning is issued for if, else, while, and
for clauses with a guarded statement that does not use braces,
followed by an unguarded statement with the same indentation.
In the following example, the call to “bar” is misleadingly indented
as if it were guarded by the “if” conditional.
if (some_condition ())
foo ();
bar (); /* Gotcha: this is not guarded by the "if". */
In the case of mixed tabs and spaces, the warning uses the -ftabstop=
option to determine if the statements line up (defaulting to 8).
The warning is not issued for code involving multiline preprocessor
logic such as the following example.
if (flagA)
foo (0);
#if SOME_CONDITION_THAT_DOES_NOT_HOLD
if (flagB)
#endif
foo (1);
The warning is not issued after a #line directive, since this
typically indicates autogenerated code, and no assumptions can be made
about the layout of the file that the directive references.
Note that this warning is enabled by -Wall in C and C++.
Alternatively, clang-format provides:
-InsertBraces (Boolean) clang-format 15
Insert braces after control statements (if, else, for, do, and while)
in C++ unless the control statements are inside macro definitions or
the braces would enclose preprocessor directives.
But also issues a warning:
Setting this option to true could lead to incorrect code formatting
due to clang-format’s lack of complete semantic information. As such,
extra care should be taken to review code changes made by this option.
A quick google showed that SonarSource's linter has a rule for this: https://rules.sonarsource.com/cpp/RSPEC-121
I believe there's a way to use this tool for free to some extent, so it should work.
Alternatively, clang-format supports the option to just add them since v15: https://clang.llvm.org/docs/ClangFormatStyleOptions.html#insertbraces
Clang-tidy actually has a check for that, and if I remember correctly, it can also fix things automatically for you (you should of course then manually go through all the changes and make sure they're correct)
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.
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;
}
After getting in a discussion about the iOS Crypto Flaw also discussed on Ars Technica, someone mentioned that they encountered a case where, the line following a bracket-less if expression, was treated as an else.
if (<condition>)
<expression A>;
<expression B>;
<expression C>;
So, according to the person, expression B would be skipped if the condition was true, as if the else is implicit and unnecessary.
This in contrary to anything I've heard - my experience has been if the condition is true, then all three expressions would be executed - but seeing as I am a pro-bracket advocate, my experience may be limited, so I was hesitant to completely call the person out. Instead, I spent about 10 minutes clarifying and making sure I correctly understood what they were saying :)
Is there any truth in what they said? What language?
I'm pretty sure all major scripting languages follow my understanding. I think the person has a greater background in Objective-C. But if this is true, it could certainly be greatest reason to always use brackets.
That would be highly illogical and I strongly doubt any language with such syntax rules would gain much support (although the languages I choose to use all have syntax I'd prefer were different, so it's certainly possible).
Any possible way (I could think of) of implementing this would result in either seemingly inconsistent behaviour when looking at other syntax rules in the language, or very restricting in terms of what's possible, and, either way, initially detrimental to readability - if it has the same indentation, how would you then have an if-statement with multiple lines in its block, or would this be disallowed? If the else part would have reduced indentation instead, how would you differentiate between code that is part of the else, or code that is just after the if-statement, or must every if-statement have an else part? And multi-line else would also be a problem either way. If it's purely based on when there is or isn't curly braces or similar, this will just be really confusing to start.
That said, there's also esoteric languages, which is really has an "anything goes" motto.
An esoteric programming language (sometimes shortened to esolang) is a programming language designed to test the boundaries of computer programming language design, as a proof of concept, or as a joke.
I wouldn't be surprised, nor would it be particularly meaningful, if there were an esoteric language with such syntax rules.
An alternative is perhaps that the person was looking at a situation like this:
<type> someFunction()
{
if (<condition>)
return <expression A>;
return <expression B>;
}
This would be synonymous to an explicit else before the second return statement, as the return statement in the if-statement would cause the return statement following it to only be executed when the condition is false.
This question already has answers here:
When do extra parentheses have an effect, other than on operator precedence?
(2 answers)
Closed 3 years ago.
Usually auto-generated c++ "main" function has at the end
return (0);
or
return (EXIT_SUCCESS);
But why there are parentheses in above statements? Is it related to C language or something?
// EDIT
I know this is correct, but someone put these brackets for a reason. What's the reason?!
They are not required (even in c). I think some people use them to make 'return' look more like a function call, thinking it is more consistent.
Edit: It's likely the generator does this for it's own reasons. It may be safer or easier for it to work this way.
But why there are parentheses in above
statements? Is it related to C
language or something?
No. As far as I can tell, C has never required parentheses for return statements. This appears to have been the case even before the first ANSI C standard.
This is actually a very interesting question, however, as I've seen that style prevalent among certain C programmers.
I think the most likely guess as to why this style came about is because all other branching statements (for, while, if, switch) require parentheses around expressions. People might have been unaware that they could omit the parentheses for return statements or were aware of this but wanted to achieve a more uniform look to their code.
The ternary ?: operator is sort of an exception as it is an operator and doesn't require parentheses around the conditional expression, yet people often write parentheses there as well regardless of whether it's needed. Some might find it serves to 'group' an expression into a single unit visually.
My second best guess is that this style was influenced by other languages popular at the time. However, popular, procedural alternatives at the time like Pascal did not require that syntax either (Pascal did not even have return values in the C sense but only output parameters) so if this is the case, I'm not aware of any particularly language from which this style originated.
[Subjective] I prefer styles that require the least amount of superfluous decoration to the code whether it comes to naming conventions or how to format it or whether to use additional parentheses where unnecessary. I find that any such decoration tends to be a matter of unique personal preference and falling in love with one way of decorating code just means that someday you'll have to deal with a completely different way (unless you work strictly alone, in which case I envy you). [/Subjective]
This is actually a requirement for BSD kernel source file style.
man 9 style says:
Space after keywords (if, while, for, return, switch).
and
Values in return statements should be enclosed in parentheses.
As any valid expression can be passed to return, those brackets can be added if desired. It is like doing this:
int i = (0);
You can nest an expression in as many brackets as you like:
return (((((0)))));
Things changes with the use of decltype(auto) in c++14 to deduce return type. If parentheses are used then returned type is deduced to be a reference:
decltype(auto) foo1() {
int n;
return (n); // parentheses causes return type to be int&
}
decltype(auto) foo2() {
int n;
return n; // no parentheses causes return type to be int
}
template<typename T> struct TD;
int main()
{
// main.cpp:19:22: error: aggregate 'TD<int&()> f1' has incomplete type and cannot be defined TD<decltype(foo1)> f1;
TD<decltype(foo1)> f1;
// main.cpp:20:22: error: aggregate 'TD<int()> f2' has incomplete type and cannot be defined TD<decltype(foo2)> f2;
TD<decltype(foo2)> f2;
}
There's a dumb reason - to make return look more like a function call.
There's a smarter reason - if the code is generated, code generators often "play it safe" by putting parentheses around expressions just so they never have to be concerned about the precedence leaking out.
Just my silly speculation:
#define RETURN(val) { if (val) printf("Main Exit With Error %d\n", val); return val; }
int main(argc, argv)
{
...
RETURN (E_FILENOTFOUND);
}
Those are not required. Maybe they come from the tendency to prefer more brackets to fewer brackets when writing macros.
Since you mention auto-generated code it might happen that the code used for generating macros was written by reusing code for generating macros or by a person who thought that more brackets won't hurt, but fewer brackets can be fatal.
One reason I can see for this:
return (ERROR_SUCCESS);
is that it's expressing the concept that ERROR_SUCCESS is opaque. We all know it's 0L, but we shouldn't have to.
That's a fairly weak reason.
Another is that it's aesthetically pleasing to use parentheses for consistency, another weak reason.
So in other words, I don't use it myself, but wouldn't flip out if someone else did. :)