Home > Articles

A Word on C

  • Print
  • + Share This

Code Bodies

Now that we've evaluated the definition of the parameter list and return type for main, let us consider the function's body:

2: {
3:   printf("Hello World");
4:
5:   return( 0 );
6: }

With any body of code, you must inform the compiler where the body begins ({) and ends (}).

In the previous example, no automatic variables are defined in the body of main; however, when automatic variables are defined, they must be placed immediately after the open brace marking the beginning of the code body.

EXCURSION

Where to Define Code Bodies in the C Language

Code bodies can be placed anywhere within a function and they can be nested. Code bodies define functions and associate a body of code with a loop or decision; however, code bodies can also be unconditional within a function. For instance, it is valid to have code bodies within bodies:

1: int main( int argc, char *argv[ ] )
2: { // start of function body
3:   int done = 0;
4:   printf( "Hello World" );
5:   { // start of unconditional body
6:     while( !done ) { // conditional body
7:       /* do something */
8:     } // end while
9:   } // end of unconditional body
10:   return( 0 );
11: } //end function body

Notice the automatic variable done in this example. The declaration of done occurs immediately after the start of a code body, specifically, the function's body; however, variables can be declared after any start-of-body marker.

EXCURSION

A Stylistic Note...

When code bodies are added to functions (as in the preceding code), it is a courtesy for those who follow behind you, and it also increases the readability of the code and adds a level of indentation to the code contained in a body. For instance, the code in the first body would be tabbed once, the code in the second body twice, and so on, with the associated begin and end body markers always in the same column. Consider the previous example without using any indentation and without the benefit of comments:

1: int main( int argc, char *argv[ ] )
2: {
3: int done = 0;
4: printf( "Hello World" );
5: {
6: while( !done ) {
7: /* do something */
8: }
9: }
10: return( 0 );
11: }

Only by carefully studying the sample can you determine the relationships between the various code bodies illustrating the utility of proper indentation.

When automatic variables are declared within a new body of code, they are governed by rules of visibility known as scope.

 

  • + Share This
  • 🔖 Save To Your Account

Related Resources

There are currently no related titles. Please check back later.