The Correct Way To Write C if-Statements by Jim Minton Mark Boolootian - booloo@llnl.gov - +1 510 423 1948 Introduction This report is the result of a single meeting held by a committee of people dedicated to wrenching whatever sanity can be found from the chaotic mess known as the C language. At the first meeting, which was held in secret, the two people on the committee came to an agreement on how C if-statements should be constructed. At future meetings other C statements will be discussed and defined. As these meetings take place and decisions are made, reports such as this will be generated. At the first meeting the possibility of adding more members to the committee was discussed, but this proposal was voted down because it was felt that other members might have opinions different from those held by the current members and would therefore make it much more difficult to come to a consensus. The current committee has had enough trouble hammering out these hard, but necessary decisions. It should be noted that all decisions in this and following papers are fully binding and everyone is expected to immediately adhere to the policies and suggestions outlined herein. The Committee By some extraordinarily fortunate quirk of nature the committee was made up of a rare group of extraordinary individuals who are blessed with uncommon insight and intelligence. These individuals possess no biases or prejudices. It is a rare moment in history when exactly the right people are gathered together at the right moment to solve a great and pressing problem, but such a moment did occur and we are now able and pleased to share the results. Problem Description Let us begin with a brief technical description. The C language has been designed so that there are several thousand possible ways to write any simple if-statement. This allows great flexibility and insures that no two programmers anywhere in the universe will ever write an if-statement that looks like any other. As can quickly be seen, however, this sometimes makes it troublesome to read Code Recorded by Another Programmer (CRAP)[1]. Of course there never has been any problem reading one's own code and this note would not be necessary if all we ever had to read was our own code. However, (Sigh), it is very often the case that we have to read CRAP[2]. An important point to remember, and one we hope is strongly reinforced by reading CRAP, is that when other people read our code, it is CRAP to them! Now here, you see, we have an opportunity to do good-when producing CRAP for other people we can either show our baser meaner natures and try to get even, or we can rise above such pettiness and try to produce something that others will refer to as good CRAP. We all should, in fact, strive to make others refer to our code as "good CRAP." This is in fact the origin of the phrase, "There's nothing like a good CRAP," which should, and probably will, become the motto of our Department. But let us return to the subject of this paper which is The Correct Way To Write C if-statements. As previously stated there are many ways an if-statement can be written. This is in fact the problem. If there were only one way to write an if-statement then we would all write them that way and each of us would be able to easily and quickly recognize them. Now, if it is the case that we could quickly and easily recognize them, if they were all written the same way, how about a novel proposal-we propose that we all write them the same way! Further, we propose that we do this despite our natural inclination to do otherwise! The Comma Operator Before proceeding with the following discussions we must first state our policy regarding the comma operator. The comma operator is not allowed. The comma operator is forbidden. The comma operator must never be used. The comma operator should be removed from the language. The comma operator is an abomination. The comma operator has produced more confusion than even the most gifted politician. We hope everyone understands our feelings about the comma operator. White Space Some people are so stingy with white space we can only wonder if they live in a cave with no lights and prefer dark and gloomy things. Are these people trying to save paper? Since most code is viewed on some sort of electronic monitor, saving paper seems to be a strange goal. And even if the code is looked at on paper, how much paper is being saved anyway? Are the savings worth the obfuscation and lack of readability that's caused? The answer is simply, "No." We loudly proclaim that writing readable code should be everyone's primary goal. Remember that we are trying to make people refer to our code as good CRAP. Effective use of white space can help achieve this goal. There is absolutely nothing wrong with using plenty of white space and in fact it should be used in abundance. "But I can't see the code." Have you ever heard anyone use this statement as an objection to white space and/or code comments? I think we all have. These people are to be shunned and avoided as if they were lepers. If they produce code for you this code will be unreadable and undocumented. The only one who will be able to read it will be the author who "wants to see the code." All other people will refer to this code as bad CRAP. People who "want to see the code" can single-handedly ruin an entire project. All of the code produced by these people will have to be rewritten. If you ever hear someone mouth this phrase you should immediately notify your supervisor and seek purification by spreading several pounds of white space around your office. Indenting if-statements As do most programmers, we feel that the body (the statements following the if) of an if-statement should be indented. We realize there are some die-hard, pinko-perverts out there who, looking for job security and trying to win obfuscated C contests, won't indent anything. If you are not a member of this latter group then you undoubtedly agree with us and the only thing left to decide is, "How far to indent?" People who indent only 1 space might as well not indent at all. No one can tell they are trying to indent and it looks as if they are randomly starting lines in columns near and about column 1. "1" is out. Indenting 2 spaces is a possibility, however 2 is awfully close to 1. "2" is out. "3" is not a power of 2. "3" is out. "4", Ah Hah! "4" is a power of two and is also the number of fingers on your right hand! It seems as though nature itself has selected an indentation level of "4!" Numbers greater than 4 are either not a power of 2 or are so large that just a few indentations immediately force us to (or past) the right margin. All numbers greater than 4 are out. The indentation level is 4 spaces! Braces Braces belong on children's teeth and around the body of every single if-statement. There are no exceptions. Every single if-body is to be surrounded by braces. The essence of the argument in favor of braces is this: all if-statements should look the same, therefore, if some if-statements have braces (as all with multi- statement bodies do) and others (those with single statement bodies) don't, then it is impossible for if-statements to look the same. Either they all have braces or none of them have braces. Since the language requires that some if-statements have braces, then, to make them all look the same, we have to put braces around every single if-body, even bodies that have only one statement! Another argument in favor of braces is the fact that braces "open the code up" and allow it to be more easily seen and read. For example compare the following two if-statements: if(ExampleOfBunchedUpCode()) UnReadable=Congested+Constipated+AnalRetentiveCode; if ( OpenCode ) { APleasureToRead = Attractive = Airy + Open + Breezy; } The first example is bunchedupandhardtoread. The second example, through the use of braces, is open, airy, and easy to examine and read. The use of braces forces the use of white space which naturally makes things easier to read. If braces are always guaranteed then we never have to wonder if the line following an if is part of the if-expression or is perhaps an if-body containing only one statement. The following example: if (((Error = Sub1(Abc, Sub2(XYZ), PDQ), < 0)) || ( a + b + c <= 75 )) illustrates our point. No one will be fooled or confused while making a quick visual scan of the preceding if-statement if they know that all if-statement bodies are surrounded by braces. The preceding sentence contains a point that is so important it must be explicitly emphasized-when reading CRAP we always try to make a "quick visual scan." If CRAP is properly written we will never be fooled and it must always be our goal to never fool anyone else. Where To Place The Braces Now that we agree to always have braces we must decide where to put them. There are some people who like to put the opening left brace way over out of sight to the right of the if-statement. We can only suppose they are ashamed of the brace or are purposefully trying to produce code that others would consider bad CRAP. The placement of the opening left brace is critical; with it you can inform the reader where the if-block will end. The if-block will end with a closing right brace that is indented at exactly the same level. The braces can be used to "sight along." Properly placed they can make CRAP easy to read and scan. if ( WeUseBraces() ) { Properly = WeCan + SightAlong + Them; } In the preceding examples you may have noticed that no other characters have been placed on a line that contains a brace. It is always the case that no other characters are allowed on a line containing an opening left brace. However it is allowed and considered good form to put a comment on the closing right brace as in the following example: if ( AnIfBlock ) { HasManyStatements(0); . . The = Last + Statement + Fini; } /* End of ( AnIfBlock ) test. */ If comments were allowed on the opening left brace the code would begin to appear dark and dense and foreboding. Since code must always appear open, airy, and inviting, comments on the opening left brace are not allowed. else-Statements Almost all of the arguments that apply to if-statements also apply to else-statements. A properly formed if-statement which contains an else-clause follows: if ( SomeDarnThing == TRUE ) { /* * A very informative comment. */ WeDoTheTRUEThing( Abc ); } else { WeDoTheFALSEThing( Abc ); } /* End of ( SomeDarnThing == TRUE ) test. */ Notice the comment that follows the last right brace. Comments are only allowed on the last right brace. It would, for example, be highly improper to put a comment after the right brace that precedes the else-statement. It is important in the preceding example to notice that it is open, airy, and easy-to-read. Always remember our motto: There's nothing like a good CRAP! NOTES [1] Years ago Sam Mendicino observed that every time someone picks up someone else's code the first thing they say is that the code is CRAP. Unfortunately, at that time, there was some misunderstanding of the intent of this statement. Some people mistakenly thought Sam was saying the code was crap. This was of course ridiculous! Sam was merely pointing out the obvious fact that this was Code Recorded (or written) by Another Programmer or just simply "CRAP." [2] The original acronym was "CWAP" (for Code Written by Another Programmer). Unfortunately this acronym makes the speaker sound like Porky Pig, as in "You Wascally Wabbit." To avoid having world leading scientists at a large prestigious laboratory sound like Porky Pig, the acronym was changed to CRAP.