if (victor(human)) { human_wins++; printf("I am your humble servant.\n"); } else { computer_wins++; printf("Your destiny is under my control!\n"); }Why do we do this? Because this makes it easy for the reader to understand which actions are performed as part of the IF-ELSE statement. The alternative (no indentation) is much harder to understand:
if (victor(human)) { human_wins++; printf("I am your humble servant.\n"); } else { computer_wins++; printf("Your destiny is under my control!\n"); }Sure, you can figure it out, but you have to work at it. Do you like to struggle to comprehend the logic of other people's programs? Of course not. Apply this observation to your own code.
int main (int argc, char *argv[]) { int a, /* an integer variable */ b; /* another lousy comment */ float c; /* always write informative comments! */ printf("Give me an 'a' : "); scanf("%d",&a); printf(" Give me a 'b' : "); scanf("%d",&b); . . . }
#include <stdio.h> int function_a (int z) { . . . } int function_b (char y) { . . . } int function_c (float x) { . . . } int main (void) { . . . }C doesn't permit functions to be nested within other functions, so we don't have to worry about how to handle that situation.
int binary_search (struct collection list[], int first_index, int last_index, key_type target);Or maybe this:
int binary_search (struct collection list[], int first_index, int last_index, key_type target );But don't do this:
int binary_search (struct collection list[], int first_index, int last_index, key_type target);
if (victor(human)) { human_wins++; printf("I am your humble servant.\n"); } else { computer_wins++; printf("Your destiny is under my control!\n"); }A minor disadvantage of this method is that it consumes a lot of lines. Now, lines are not expensive, but programmers like to be able to place a lot of code on the screen at one time, and this method "wastes" lines.
if ( (!victor(human)) && (!victor(computer)) ) { number_of_draws++; printf("We are well-matched.\n"); }
if (count < 0) count = 0;By placing the (indented) body on the next line, you make the whole statement (and also its purpose) much easier to identify:
if (count < 0) count = 0;I maintain that it is not a bad idea to go ahead and place braces around these one-statement bodies, too. The reason: Should you later decide to add a statement to the body, you don't have to remember to add the braces to complete the compound statement:
if (count < 0) { count = 0; }
if ( (!victor(human)) && (!victor(computer)) ) { number_of_draws++; printf("We are well-matched.\n"); }
if (temperature < 55) printf("It could be warmer...\n"); else printf("It could be colder...\n");If we add braces to this, how should we align them? You can align the braces, of course, as we did in one of the previous examples. Otherwise, you might choose to align both closing braces with the "i" in "if". Here's the same example with that brace alignment:
if (temperature < 55) { printf("It could be warmer...\n"); } else { printf("It could be colder...\n"); }I like this approach, because I think it helps to tie the entire IF-ELSE statement together.
if (victor(human)) { human_wins++; printf("I am your humble servant.\n"); } else { computer_wins++; printf("Your destiny is under my control!\n"); }
if (square_footage > 2500) { tax = square_footage * 0.025; printf("Do you need a loan?\n"); } else tax = 0;That just looks funny to me, but it's perfectly acceptable. As you already know, I'm partial to the idea of "bracing" even the simple bodies:
if (square_footage > 2500) { tax = square_footage * 0.025; printf("Do you need a loan?\n"); } else { tax = 0; }
switch(letter) { case ' ': printf("This is a space,\n"); break; case 'a': case 'e': case 'i': case 'o': case 'u': printf("This is a vowel.\n"); break; default: printf("This is is something else.\n"); }I've never liked that approach; to me, aligning all of those CASEs with the SWITCH breaks up the flow of the statement, and makes it too hard to recognize the end of the SWITCH. I prefer to indent the CASEs from the SWITCH, and then indent the statements from the CASES in a slightly different way:
switch(letter) { case ' ': printf("This is a space,\n"); break; case 'a': case 'e': case 'i': case 'o': case 'u': printf("This is a vowel.\n"); break; default : printf("This is is something else.\n"); }What makes this acceptable? The indentation is consistent, and the closing brace aligns with the corresponding statement. So long as I stick with this style for all SWITCH statements in the program, there's no problem.
i = 0; while ((i < LIST_SIZE) && (list[i] != MAX_SCORE)) i++;Instead, make it a habit to place the indented body on the next line:
i = 0; while ((i < LIST_SIZE) && (list[i] != MAX_SCORE)) i++;And if you're like me, you will add the braces just to be safe:
i = 0; while ((i < LIST_SIZE) && (list[i] != MAX_SCORE)) { i++; }It is possible to have a WHILE loop that doesn't have any statements in its body. See the discussion of the FOR loop with a Simple Body later in this page for ideas on how to handle this situation.
i = 0; while (i < LIST_SIZE) { printf("Element %d is %d.\n",i,list[i]); i++; }
for (i=0; (i < LIST_SIZE) && (list[i] != MAX_SCORE); i++); if (i >= LIST_SIZE) printf("Sorry; %d was not found.\n",MAX_SCORE);There's no body! Looks strange, doesn't it? Worse, it looks confusing; the semicolon at the end is easy to overlook, which might lead the reader to believe that the "if" statement is the loop's body. To help the reader, it is best to place the semicolon on the next line:
for (i=0; (i < LIST_SIZE) && (list[i] != MAX_SCORE); i++) ; if (i >= LIST_SIZE) printf("Sorry; %d was not found.\n",MAX_SCORE);Even better, put a comment with it:
for (i=0; (i < LIST_SIZE) && (list[i] != MAX_SCORE); i++) /* null loop body */ ; if (i >= LIST_SIZE) printf("Sorry; %d was not found.\n",MAX_SCORE);Apart from that situation, just indent the FORs like you would the WHILEs:
for (i=0; i < LIST_SIZE; i++) printf("Element %d is %d.\n",i,list[i]);
for (sum=0, i=0; i < LIST_SIZE; i++) { printf("Element %d is %d.\n",i,list[i]); sum += list[i]; }
i = -1; do i++; while ((i < LIST_SIZE) && (list[i] != MAX_SCORE));If you don't care for that style (and I don't blame you), you can place the parts on separate lines and indent the body from the level of the DO and WHILE keywords:
i = -1; do i++; while ((i < LIST_SIZE) && (list[i] != MAX_SCORE));The problem with this approach is that the reader might get confused by the word "while" on the left edge; it would be easy to mistake the "while" of the DO-WHILE loop for the "while" that starts the WHILE loop. If you are of the habit of always adding braces around loop bodies, you can use the closing brace to avoid confusion:
i = -1; do { i++; } while ((i < LIST_SIZE) && (list[i] != MAX_SCORE));
i = 0; do { printf("Element %d is %d.\n",i,list[i]); i++; } while (i < LIST_SIZE);The "do" seems to be a little lost on a line by itself, but there's nothing wrong with this. I prefer the look of the loop with the closing brace aligned with the "do" only:
i = 0; do { printf("Element %d is %d.\n",i,list[i]); i++; } while (i < LIST_SIZE);
[0] int main (void) [0] { [1] int i; [1] float sum = 0, thousandth = 0.001; [1] for (i=1; i<=1000; i++) { [2] sum += thousandth; [2] if (i % 100 == 0) [3] printf("After %4d iterations, sum = %.10f\n",i,sum); [1] } [1] printf("\nUsing %%.2f in printf rounds sum to be %.2f,\n",sum); [1] if (sum != 1.00) [2] printf("but C says that sum does not equal 1.00.\n"); [1] else [2] printf("and C says that sum does equal 1.00.\n"); [1] return 0; [0] }The observation to make is that the body of a statement is one level deeper than the statement's own level. This is how nested statements are supposed to be indented; always indent the bodies from the level of the corresponding statement.
if (score >= 89.5) grade = 'A'; else if (score >= 79.5) grade = 'B'; else if (score >= 69.5) grade = 'C'; else if (score >= 59.5) grade = 'D'; else grade = 'F';This is a good example of the "stair-step effect" that results from this sort of nesting. If there are only a few levels of nesting, there is no problem. But if there are a lot of levels, or if the code with each level is of even moderate complexity, we'll find that we are running out of room to write statements on each line. Instead of creating clear, easy-to-read code, we'll be creating a mess along the right side of the screen.
if (score >= 89.5) grade = 'A'; else if (score >= 79.5) grade = 'B'; else if (score >= 69.5) grade = 'C'; else if (score >= 59.5) grade = 'D'; else grade = 'F';As I said, not as nice, but more functional.
#include <stdio.h> int main(void) { int seg[10] = {6,2,5,5,4,5,6,3,7,6}; int d1, d2, d3, d4, m=0, td, ts; for (d1=0; d1<2; d1++) for (d2=0; d2<10; d2++) for (d3=0; d3<6; d3++) for (d4=0; d4<10; d4++) if ((!((d1==0)&&(d2==0))) && (!((d1==1)&&(d2>2)))) { if (d1==0) { ts = seg[d2] + seg[d3] + seg[d4]; td = d2 + d3 + d4; if (ts == td) { m++; printf(" %1d:%1d%1d\n",d2,d3,d4); } } else { ts = seg[d1] + seg[d2] + seg[d3] + seg[d4]; td = d1 + d2 + d3 + d4; if (ts == td) { m++; printf("%1d%1d:%1d%1d\n",d1,d2,d3,d4); } } } return 0; }