Finding statement pattern in c++ file - c++

I have a macro that looks like this:
#define coutError if (VERBOSITY_SETTING >= VERBOSITY_ERROR) ods()
where ods() is a class that behaves similarly to cout, and VERBOSITY_SETTING is a global variable. There are a few of these for different verbosity settings, and it allows the code to look something like this:
if (someErrorCondition)
{
// ... do things relating to the error condition ...
coutError << "Error condition occurred";
}
And there is functionality in this framework to set the verbosity, etc. However, the obvious pattern breaks when not using braces in something like this:
void LightSwitch::TurnOn()
{
if (!PowerToSwitch)
coutError << "No power!";
else
SwitchOn = true;
}
because of the macro, will turn into this:
void LightSwitch::TurnOn()
{
if (!PowerToSwitch)
if (VERBOSITY_SETTING >= VERBOSITY_ERROR)
ods() << "No power!";
else
SwitchOn = true;
}
Which is not the intended functionality of the if statement.
Now, I understand a way to fix this macro properly so it doesn't cause this problem, but I'd like to run an audit on the code and find any place that has this pattern of "if (...) coutError << ...; else" to find out if there are any other cases where this happens to make sure that when fixing the macro, it will indeed be correct functionality.
I can use any language/tool to find this, I just want to know the best way of doing that.

You could try - temporarily - modifying the macro to something like this, and see what doesn't compile...
#define coutError {} if (VERBOSITY_SETTING >= VERBOSITY_ERROR) ods()
The 'else' clauses should now give errors.

Don't bother trying to find all of the locations in your code where a logic error is occurring -- fix the problem at its source! Change the macro so that there's no possibility of error:
#define coutError if(VERBOSITY_SETTING < VERBOSITY_ERROR); else ods()
Note that what I've done here is inverted the test, added an empty statement for the then clause, and put the output object in the else clause. This still allows you to use << foo << bar after the macro, and if you have a trailing else clause belonging to a different if statement, it will get matched up properly, since it expands like so:
if(foo)
coutError << bar;
else
baz();
becomes
if(foo)
if(VERBOSITY_SETTING < VERBOSITY_ERROR)
;
else
ods() << bar;
else
baz();

I think all good usages of the macro are preceeded with '{' or ';'.
So try this regular expression:
[^{;]\s*coutError
You'll need to turn on multi-line matching and search against entire files.
You might need to grab more stuff so that you can locate the line in question :-)
Alternatively changing the macro is a neat idea, if we can work out something that will fail correctly. Maybe a block followed by the conditional operator:
#define coutError {} (VERBOSITY_SETTING >= VERBOSITY_ERROR)?(ods()):(nullstream())
(But does require implementing a nullstream() operator.)
(Alternatively get rid of the conditional entirely temporarily - as you suggest is a comment to another answer #Roddy (currently the selected answer)).
p.s. I know you didn't ask, but an easy way to wrap the macro to make it safe is with a do {} while(false) loop.

I see in your comments above that you're thinking of using a template in the macro, and I can't comment yet (I'm 9 points short of it), so...
What stops you from doing
#define CoutError(s) { if (VERBOSITY_SETTING >= VERBOSITY_ERROR){ ods(s); } }
And then
void LightSwitch::TurnOn()
{
if (!PowerToSwitch)
CoutError("No power!");
else
SwitchOn = true;
}
And redefine ods to admit a string, or alternatively if you can't, then just define an OdsHelper function which takes a string and whose body is simply ods << inString?
I wouldn't play with macros trying to mimic the << syntax if there is no clear gain. At least with macros simulating the function syntax we're more used and we know we have to write the blocks to prevent strange issues.
Do you really need the << syntax?
And do you really need to introduce a template for this simple behaviour?
Oh and one last thing - don't use macros.

I think the real problem is the use of the macro - not the code that gets preprocessed. But I don't think this is the answer you are looking for.
I would find a way to do it without using macros at all - and if you do use conditional compiles you can do so in the call to ods() - depending on some #define it can use whatever functionality you want.
just my $.02

regular expression search?

Related

Name for phenomenom: if if else

Last week I heared about a phenomenom about if-Statements. It had a specific name, but I can't remember it.
The Problem is about an if-if-else construction, for example:
if( a!=null )
if( a.isTrue() )
a.performAction();
else
a.healCondition(); // second chance to do something
So the problem comes from missing brackets. It wouldn't be a problem if I use brackets for the outer if.
Without brackets it is not always clear to which "if" the "else" belongs to.
But I don't want to have a solution for that problem. I would be happy to know how this pattern is called.
Thanks for your help
The ambiguity is called dangling else, and how it's solved depends on the language. Java for example has syntax rules that associate else with the inner if.
This looks like Java, but what I am saying applies to almost every "bracketed" language.
You should really try not to use multiline if statements when you don't want to use brackets.
In this case you would not want to write:
if(a!=null) if(a.isTrue()) a.performAction(); else a.healCondition();
It is ugly, so you break it up into multiple lines. As soon as you do that you should add brackets. Not for compiler (which won't need them in this case), but for other programmers and yourself:
if(a!=null)
{
if(a.isTrue()) a.performAction();
else a.healCondidiont();
}
or
if(a!=null)
{
if(a.isTrue())
{
a.performAction();
}
else
{
a.healCondidiont();
}
}

Whats meaning of this rsAssert macro?

i found this code from here
#if 1
#define rsAssert(v) do {if(!(v)) LOGE("rsAssert failed: %s, in %s at %i", #v, __FILE__, __LINE__);} while(0)
#else
#define rsAssert(v) while(0)
#endif
Question 1:
Here i am not getting why do and while is used here? Is there any special reason for using this?
Question 2:
What is the purpose of doing this all in macro. Why just one dont use assert() ?
i think perhaps there is a valid reason for this..
Your first question about why there's a do/while "loop" is covered here: What's the use of do while(0) when we define a macro?
The answer to the second question could be better answered by the code's author, but I guess they wanted to use their own logging system when an assert failed rather than the default one.
The do/while is a well-known trick for turning a block of statements into something that syntactically acts like a single statement. It allows use in places like:
if (whatever)
rsAssert(whatever);
else
// ...
whereas, most alternatives would produce a syntax error in this case.
As for why using it at all: because it writes output with LOGE instead of printing to stderr, and (unless LOGE does so) this doesn't seem to abort the program like assert will.
As asked many times before, the reason a do-while loop is use is for syntactic sugar:
// this line would be valid if a simple if was used:
rsAssert(myAssert)
// with a do-while, however, this is now invalid:
rsAssert(myAssert)
// so, that means you have to add the ';' to make it look like a function call:
rsAssert(myAssert);

Conversion of JSON logging macros to template functions... parameter names needed in code

I was assigned the task of updating a very old project a while back. The first thing I had to do was to expand the existing code to incorporate a new feature. As part of this I modified existing macros to print JSON representations of incoming messages (over CORBA, into C++ structs). I then incorporated boost program_options and a new logger and now I want to modernise the macros.
The problem is that I have no idea how to implement what I did with the macros with templates. The key problem is that I use the name of the parameters to the macros to access the fields of the struct:
//Defines the string that precedes the variable name in a JSON name-value pair (newline,indent,")
#define JSON_PRE_VNAME _T("%s,\n\t\t\t\t\"")
//Defines the string that follows the variable name in a JSON name-value pair (":) preceding the value
#define JSON_SEP _T("\":")
#define printHex(Y,X) _tprintf(_T("%02X"), (unsigned char)##Y->##X );
// ******** MACRO **********
// printParam (StructureFieldName=X, ParamType=Y)
// prints out a json key value pair.
// e.g. printParam(AgentId, %s) will print "AgentId":"3910"
// e.g. printParam(TempAgent, %d) will print "TempAgent":1
#define printParam(X,Y) if(strcmp(#Y,"%s")==0){\
_byteCount += _stprintf(_logBuf,JSON_PRE_VNAME _T(#X) JSON_SEP _T("\"%s\""),_logBuf,myEvent->##X);\
}else{\
_byteCount += _stprintf(_logBuf,JSON_PRE_VNAME _T(#X) JSON_SEP _T(#Y),_logBuf,myEvent->##X);\
}\
printBufToLog();
And it is used like this:
//CORBA EVENT AS STRUCT "event"
else if(event.type == NI_eventSendInformationToHost ){
evSendInformationToHost *myEvent;
event.data >>= myEvent; //demarshall
printParam(EventTime,%d);
printParam(Id,%d);
printParam(NodeId,%d);
}
and this results in JSON like this:
"EventTime":1299239194,
"Id":1234567,
"NodeId":3
etc...
Obviously I have commented these macros fairly well, but I am hoping that for the sake of anyone else looking at the code that there is a nice way to achieve the same result with templates. I have to say the macros do make it very easy to add new events to the message logger.
Basically how do I do "#X" and ##X with templates?
Any pointers would be appreciated.
Thanks!
There are some things that you cannot really do without macros, and for some specific contexts macros are the solution. I would just leave the macros as they are and move on to the next task.
Well, I would actually try to improve a bit the macros. It is usually recommended not to use ; inside macros, and with macros that contain more than a single statement wrap them in do {} while(0) loops:
#define printHex(Y,X) _tprintf(_T("%02X"), (unsigned char)##Y->##X )
// remove ; ^
// add do while here:
#define printParam(X,Y) do { if(strcmp(#Y,"%s")==0){\
_byteCount += _stprintf(_logBuf,JSON_PRE_VNAME _T(#X) JSON_SEP _T("\"%s\""),_logBuf,myEvent->##X);\
}else{\
_byteCount += _stprintf(_logBuf,JSON_PRE_VNAME _T(#X) JSON_SEP _T(#Y),_logBuf,myEvent->##X);\
}\
printBufToLog();\
} while (false)
This might help avoid small mistakes that would otherwise be hard to fix, as, for example uses of the macros with if:
if (condition) printHex(a,b);
else printHex(c,d);
// looks good, but would originally expand to a syntax error:
if (condition) _tprintf(_T("%02X"), (unsigned char)##Y->##X );;
else ...
Similarly
if (condition) printParam(a,b);
else ...
would expand to a whole lot of non-sense for the compiler even if it looks correct enough to the casual eye.
I think that in many cases it's better to use an external code generator... starting from a nice neutral definition it's easy to generate C++, Javascript and whatnot to handle your data.
C++ templates are quite primitive and structure/class introspection is just absent. By playing some tricks you can be able to do ifs and loops (wow! what an accomplishment) but a lot of useful techniques are just out of reach. Also once you get your hard to debug template trickery working, at the first error the programmer makes you get screens and screens of babbling nonsense instead of a clear error message.
On the other side you have the C preprocessor, that is horribly weak at doing any real processing and is just a little more (and also less) than a regexp search/replace.
Why clinging to poor tools instead of just implementing a separate code generation phase (that can easily be integrated in the make process) where you can use a serious language of your choice able to do both processing and text manipulation easily?
How easy would be to write a neutral easy-to-parse file and then using for example a Python program to generate the C++ struct declarations, the serialization code and also the javascript counterpart for that?

do {...} while(false)

I was looking at some code by an individual and noticed he seems to have a pattern in his functions:
<return-type> function(<params>)
{
<initialization>
do
{
<main code for function>
}
while(false);
<tidy-up & return>
}
It's not bad, more peculiar (the actual code is fairly neat and unsurprising). It's not something I've seen before and I wondered if anyone can think of any logic behind it - background in a different language perhaps?
You can break out of do{...}while(false).
A lot of people point out that it's often used with break as an awkward way of writing "goto". That's probably true if it's written directly in the function.
In a macro, OTOH, do { something; } while (false) is a convenient way to FORCE a semicolon after the macro invocation, absolutely no other token is allowed to follow.
And another possibility is that there either once was a loop there or iteration is anticipated to be added in the future (e.g. in test-driven development, iteration wasn't needed to pass the tests, but logically it would make sense to loop there if the function needed to be somewhat more general than currently required)
The break as goto is probably the answer, but I will put forward one other idea.
Maybe he wanted to have a locally defined variables and used this construct to get a new scope.
Remember while recent C++ allows for {...} anywhere, this was not always the case.
I've seen it used as a useful pattern when there are many potential exit points for the function, but the same cleanup code is always required regardless of how the function exits.
It can make a tiresome if/else-if tree a lot easier to read, by just having to break whenever an exit point is reached, with the rest of the logic inline afterwards.
This pattern is also useful in languages that don't have a goto statement. Perhaps that's where the original programmer learnt the pattern.
I've seen code like that so you can use break as a goto of sorts.
I think it's more convenient to write break instead of goto end. You don't even have to think up a name for the label which makes the intention clearer: You don't want to jump to a label with a specific name. You want to get out of here.
Also chances are you would need the braces anyway. So this is the do{...}while(false); version:
do {
// code
if (condition) break; // or continue
// more code
} while(false);
And this is the way you would have to express it if you wanted to use goto:
{
// code
if (condition) goto end;
// more code
}
end:
I think the meaning of the first version is much easier to grasp. Also it's easier to write, easier to extend, easier to translate to a language that doesn't support goto, etc.
The most frequently mentioned concern about the use of break is that it's a badly disguised goto. But actually break has more resemblance to return: Both instructions jump out of a block of code which is pretty much structured in comparison to goto. Nevertheless both instructions allow multiple exit points in a block of code which can be confusing sometimes. After all I would try to go for the most clear solution, whatever that is in the specific situation.
This is just a perversion of while to get the sematics of goto tidy-up without using the word goto.
It's bad form because when you use other loops inside the outer while the breaks become ambiguous to the reader. "Is this supposed to goto exit? or is this intended only to break out of the inner loop?"
This trick is used by programmers that are too shy to use an explicit goto in their code. The author of the above code wanted to have the ability to jump directly to the "cleanup and return" point from the middle of the code. But they didn't want to use a label and explicit goto. Instead, they can use a break inside the body of the above "fake" cycle to achieve the same effect.
Several explanations. The first one is general, the second one is specific to C preprocessor macros with parameters:
Flow control
I've seen this used in plain C code. Basically, it's a safer version of goto, as you can break out of it and all memory gets cleaned up properly.
Why would something goto-like be good? Well, if you have code where pretty much every line can return an error, but you need to react to all of them the same way (e.g. by handing the error to your caller after cleaning up), it's usually more readable to avoid an if( error ) { /* cleanup and error string generation and return here */ } as it avoids duplication of clean-up code.
However, in C++ you have exceptions + RAII for exactly this purpose, so I would consider it bad coding style.
Semicolon checking
If you forget the semicolon after a function-like macro invocation, arguments might contract in an undesired way and compile into valid syntax. Imagine the macro
#define PRINT_IF_DEBUGMODE_ON(msg) if( gDebugModeOn ) printf("foo");
That is accidentally called as
if( foo )
PRINT_IF_DEBUGMODE_ON("Hullo\n")
else
doSomethingElse();
The "else" will be considered to be associated with the gDebugModeOn, so when foo is false, the exact reverse of what was intended will happen.
Providing a scope for temporary variables.
Since the do/while has curly braces, temporary variables have a clearly defined scope they can't escape.
Avoiding "possibly unwanted semicolon" warnings
Some macros are only activated in debug builds. You define them like:
#if DEBUG
#define DBG_PRINT_NUM(n) printf("%d\n",n);
#else
#define DBG_PRINT_NUM(n)
#endif
Now if you use this in a release build inside a conditional, it compiles to
if( foo )
;
Many compilers see this as the same as
if( foo );
Which is often written accidentally. So you get a warning. The do{}while(false) hides this from the compiler, and is accepted by it as an indication that you really want to do nothing here.
Avoiding capturing of lines by conditionals
Macro from previous example:
if( foo )
DBG_PRINT_NUM(42)
doSomething();
Now, in a debug build, since we also habitually included the semicolon, this compiles just fine. However, in the release build this suddenly turns into:
if( foo )
doSomething();
Or more clearly formatted
if( foo )
doSomething();
Which is not at all what was intended. Adding a do{ ... }while(false) around the macro turns the missing semicolon into a compile error.
What's that mean for the OP?
In general, you want to use exceptions in C++ for error handling, and templates instead of macros. However, in the very rare case where you still need macros (e.g. when generating class names using token pasting) or are restricted to plain C, this is a useful pattern.
It looks like a C programmer. In C++, automatic variables have destructors which you use to clean up, so there should not be anything needed tidying up before the return. In C, you didn't have this RAII idiom, so if you have common clean up code, you either goto it, or use a once-through loop as above.
Its main disadvantage compared with the C++ idiom is that it will not tidy up if an exception is thrown in the body. C didn't have exceptions, so this wasn't a problem, but it does make it a bad habit in C++.
It is a very common practice. In C. I try to think of it as if you want to lie to yourself in a way "I'm not using a goto". Thinking about it, there would be nothing wrong with a goto used similarly. In fact it would also reduce indentation level.
That said, though, I noticed, very often this do..while loops tend to grow. And then they get ifs and elses inside, rendering the code actually not very readable, let alone testable.
Those do..while are normally intended to do a clean-up. By all means possible I would prefer to use RAII and return early from a short function. On the other hand, C doesn't provide you as much conveniences as C++ does, making a do..while one of the best approaches to do a cleanup.
Maybe it’s used so that break can be used inside to abort the execution of further code at any point:
do {
if (!condition1) break;
some_code;
if (!condition2) break;
some_further_code;
// …
} while(false);
I think this is done to use break or continue statements. Some kind of "goto" code logic.
It's simple: Apparently you can jump out of the fake loop at any time using the break statement. Furthermore, the do block is a separate scope (which could also be achieved with { ... } only).
In such a situation, it might be a better idea to use RAII (objects automatically destructing correctly when the function ends). Another similar construct is the use of goto - yes, I know it's evil, but it can be used to have common cleanup code like so:
<return-type> function(<params>)
{
<initialization>
<main code for function using "goto error;" if something goes wrong>
<tidy-up in success case & return>
error:
<commmon tidy-up actions for error case & return error code or throw exception>
}
(As an aside: The do-while-false construct is used in Lua to come up for the missing continue statement.)
How old was the author?
I ask because I once came across some real-time Fortran code that did that, back in the late 80's. It turns out that is a really good way to simulate threads on an OS that doesn't have them. You just put the entire program (your scheduler) in a loop, and call your "thread" routines" one by one. The thread routines themselves are loops that iterate until one of a number of conditions happen (often one being a certain amount of time has passed). It is "cooperative multitasking", in that it is up to the individual threads to give up the CPU every now and then so the others don't get starved. You can nest the looping subprogram calls to simulate thread priority bands.
Many answerers gave the reason for do{(...)break;}while(false). I would like to complement the picture by yet another real-life example.
In the following code I had to set enumerator operation based on the address pointed to by data pointer. Because a switch-case can be used only on scalar types first I did it inefficiently this way
if (data == &array[o1])
operation = O1;
else if (data == &array[o2])
operation = O2;
else if (data == &array[on])
operation = ON;
Log("operation:",operation);
But since Log() and the rest of code repeats for any chosen value of operation I was wandering how to skip the rest of comparisons when the address has been already discovered. And this is where do{(...)break;}while(false) comes in handy.
do {
if (data == &array[o1]) {
operation = O1;
break;
}
if (data == &array[o2]) {
operation = O2;
break;
}
if (data == &array[on]) {
operation = ON;
break;
}
} while (false);
Log("operation:",operation);
One may wonder why he couldn't do the same with break in an if statement, like:
if (data == &array[o1])
{
operation = O1;
break;
}
else if (...)
break interacts solely with the closest enclosing loop or switch, whether it be a for, while or do .. while type, so unfortunately that won't work.
In addition to the already mentioned 'goto examples', the do ... while (0) idiom is sometimes used in a macro definition to provide for brackets in the definition and still have the compiler work with adding a semi colon to the end of a macro call.
http://groups.google.com/group/comp.soft-sys.ace/browse_thread/thread/52f670f1292f30a4?tvc=2&q=while+(0)
I agree with most posters about the usage as a thinly disguised goto. Macros have also been mentioned as a potential motivation for writing code in the style.
I have also seen this construct used in mixed C/C++ environments as a poor man's exception. The "do {} while(false)" with a "break" can be used to skip to the end of the code block should something that would normally warrant an exception be encountered in the loop.
I have also sen this construct used in shops where the "single return per function" ideology is enforced. Again, this is in lieu of an explicit "goto" - but the motivation is to avoid multiple return points, not to "skip over" code and continue actual execution within that function.
I work with Adobe InDesign SDK, and the InDesign SDK examples have almost every function written like this. It is due to fact that the function are usually really long. Where you need to do QueryInterface(...) to get anything from the application object model. So usually every QueryInterface is followed by if not went well, break.
Many have already stated the similarity between this construct and a goto, and expressed a preference for the goto. Perhaps this person's background included an environment where goto's were strictly forbidden by coding guidelines?
The other reason I can think of is that it decorates the braces, whereas I believe in a newer C++ standard naked braces are not okay (ISO C doesn't like them). Otherwise to quiet a static analyzer like lint.
Not sure why you'd want them, maybe variable scope, or advantage with a debugger.
See Trivial Do While loop, and Braces are Good from C2.
To clarify my terminology (which I believe follows standard usage):
Naked braces:
init();
...
{
c = NULL;
mkwidget(&c);
finishwidget(&c);
}
shutdown();
Empty braces (NOP):
{}
e.g.
while (1)
{} /* Do nothing, endless loop */
Block:
if (finished)
{
closewindows(&windows);
freememory(&cache);
}
which would become
if (finished)
closewindows(&windows);
freememory(&cache);
if the braces are removed, thus altering the flow of execution, not just the scope of local variables. Thus not 'freestanding' or 'naked'.
Naked braces or a block may be used to signify any section of code that might be a potential for an (inline) function that you wish to mark, but not refactor at that time.
It's a contrived way to emulate a GOTO as these two are practically identical:
// NOTE: This is discouraged!
do {
if (someCondition) break;
// some code be here
} while (false);
// more code be here
and:
// NOTE: This is discouraged, too!
if (someCondition) goto marker;
// some code be here
marker:
// more code be here
On the other hand, both of these should really be done with ifs:
if (!someCondition) {
// some code be here
}
// more code be here
Although the nesting can get a bit ugly if you just turn a long string of forward-GOTOs into nested ifs. The real answer is proper refactoring, though, not imitating archaic language constructs.
If you were desperately trying to transliterate an algorithm with GOTOs in it, you could probably do it with this idiom. It's certainly non-standard and a good indicator that you're not adhering closely to the expected idioms of the language, though.
I'm not aware of any C-like language where do/while is an idiomatic solution for anything, actually.
You could probably refactor the whole mess into something more sensible to make it more idiomatic and much more readable.
Some coders prefer to only have a single exit/return from their functions. The use of a dummy do { .... } while(false); allows you to "break out" of the dummy loop once you've finished and still have a single return.
I'm a java coder, so my example would be something like
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class p45
{
static List<String> cakeNames = Arrays.asList("schwarzwald torte", "princess", "icecream");
static Set<Integer> forbidden = Stream.of(0, 2).collect(Collectors.toSet());
public static void main(String[] argv)
{
for (int i = 0; i < 4; i++)
{
System.out.println(String.format("cake(%d)=\"%s\"", i, describeCake(i)));
}
}
static String describeCake(int typeOfCake)
{
String result = "unknown";
do {
// ensure type of cake is valid
if (typeOfCake < 0 || typeOfCake >= cakeNames.size()) break;
if (forbidden.contains(typeOfCake)) {
result = "not for you!!";
break;
}
result = cakeNames.get(typeOfCake);
} while (false);
return result;
}
}
In such cases I use
switch(true) {
case condution1:
...
break;
case condution2:
...
break;
}
This is amusing. There are probably breaks inside the loop as others have said. I would have done it this way :
while(true)
{
<main code for function>
break; // at the end.
}

Is it a bad practice to use an if-statement without curly braces? [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 7 years ago.
Improve this question
I've seen code like this:
if(statement)
do this;
else
do this;
However, I think this is more readable:
if(statement){
do this;
}else{
do this;
}
Since both methods work, is this simply a matter of preference which to use or would one way be recommended over the other?
The problem with the first version is that if you go back and add a second statement to the if or else clauses without remembering to add the curly braces, your code will break in unexpected and amusing ways.
Maintainability-wise, it's always smarter to use the second form.
EDIT: Ned points this out in the comments, but it's worth linking to here, too, I think. This is not just some ivory-tower hypothetical bullshit: https://www.imperialviolet.org/2014/02/22/applebug.html
One problem with leaving out statement blocks is the else-ambiguity. That is C-inspired languages ignore indentation and so have no way of separating this:
if(one)
if(two)
foo();
else
bar();
From this:
if(one)
if(two)
foo();
else
bar();
My general pattern is that if it fits on one line, I'll do:
if(true) do_something();
If there's an else clause, or if the code I want to execute on true is of significant length, braces all the way:
if(true) {
do_something_and_pass_arguments_to_it(argument1, argument2, argument3);
}
if(false) {
do_something();
} else {
do_something_else();
}
Ultimately, it comes down to a subjective issue of style and readability. The general programming world, however, pretty much splits into two parties (for languages that use braces): either use them all the time without exception, or use them all the time with exception. I'm part of the latter group.
The "rule" I follow is this:
If the "if" statement is testing in order to do something (I.E. call functions, configure variables etc.), use braces.
if($test)
{
doSomething();
}
This is because I feel you need to make it clear what functions are being called and where the flow of the program is going, under what conditions. Having the programmer understand exactly what functions are called and what variables are set in this condition is important to helping them understand exactly what your program is doing.
If the "if" statement is testing in order to stop doing something (I.E. flow control within a loop or function), use a single line.
if($test) continue;
if($test) break;
if($test) return;
In this case, what's important to the programmer is discovering quickly what the exceptional cases are where you don't want the code to run, and that is all coverred in $test, not in the execution block.
I am using the code formatter of the IDE I use. That might differ, but it can be setup in the Preferences/Options.
I like this one:
if (statement)
{
// comment to denote in words the case
do this;
// keep this block simple, if more than 10-15 lines needed, I add a function for it
}
else
{
do this;
}
Having the braces right from the first moment should help to prevent you from ever having to debug this:
if (statement)
do this;
else
do this;
do that;
Use braces for all if statements even the simple ones. Or, rewrite a simple if statement to use the ternary operator:
if (someFlag) {
someVar= 'someVal1';
} else {
someVar= 'someVal2';
}
Looks much nicer like this:
someVar= someFlag ? 'someVal1' : 'someVal2';
But only use the ternary operator if you are absolutely sure there's nothing else that needs to go in the if/else blocks!
I prefer using braces. Adding braces makes it easier to read and modify.
Here are some links for the use of braces:
Prefer Multiline if
Omitting Braces: Not Just A Matter Of Style
Stack Overflow
From my experience the only (very) slight advantage of the first form is code readability, the second form adds "noise".
But with modern IDEs and code autogeneration (or autocompletion) I strongly recommend using the second form, you won't spend extra time typing curly braces and you'll avoid some of the most frequent bugs.
There are enough energy consuming bugs, people just shoudn't open doors for big wastes of time.
One of the most important rule to remember when writing code is consistency. Every line of code should be written the same way, no matter who wrote it. Being rigorous prevents bugs from "happening" ;)
This is the same with naming clearly & explicitly your variables, methods, files or with correctly indenting them...
When my students accept this fact, they stop fighting against their own sourcecode and they start to see coding as a really interesting, stimulating and creative activity. They challenge their minds, not their nerves !
Personally I use the first style only throw an exception or return from a method prematurely. Like argument Checking at the beginning of a function, because in these cases, rarely do I have have more than one thing to do, and there is never an else.
Example:
if (argument == null)
throw new ArgumentNullException("argument");
if (argument < 0)
return false;
Otherwise I use the second style.
It is a matter of preference. I personally use both styles, if I am reasonably sure that I won't need to add anymore statements, I use the first style, but if that is possible, I use the second. Since you cannot add anymore statements to the first style, I have heard some people recommend against using it. However, the second method does incur an additional line of code and if you (or your project) uses this kind of coding style, the first method is very much preferred for simple if statements:
if(statement)
{
do this;
}
else
{
do this;
}
However, I think the best solution to this problem is in Python. With the whitespace-based block structure, you don't have two different methods of creating an if statement: you only have one:
if statement:
do this
else:
do this
While that does have the "issue" that you can't use the braces at all, you do gain the benefit that it is no more lines that the first style and it has the power to add more statements.
I have always tried to make my code standard and look as close to the same as possible. This makes it easier for others to read it when they are in charge of updating it. If you do your first example and add a line to it in the middle it will fail.
Won't work:
if(statement)
do this;
and this;
else
do this;
My personal preference is using a mixture of whitespace and brackets like this:
if( statement ) {
// let's do this
} else {
// well that sucks
}
I think this looks clean and makes my code very easy to read and most importantly - debug.
I agree with most answers in the fact that it is better to be explicit in your code and use braces. Personally I would adopt a set of coding standards and ensure that everyone on the team knows them and conforms. Where I work we use coding standards published by IDesign.net for .NET projects.
I prefer putting a curly brace. But sometimes, ternary operator helps.
In stead of :
int x = 0;
if (condition) {
x = 30;
} else {
x = 10;
}
One should simply do : int x = condition ? 30 : 20;
Also imagine a case :
if (condition)
x = 30;
else if (condition1)
x = 10;
else if (condition2)
x = 20;
It would be much better if you put the curly brace in.