prev

Functions

next

Functions provide a way writing modular, reusable, and readable code. A function typically encapsulates a well defined action which can then be used without worrying about its implementation. Definition
  return_type function_name ( parameter declarations ) {
    local declarations
    statements
  }
As an example here is a function which will raise the integer num to a positive integer power exp
  int power ( int num, int exp ) {
    int i,
        result = 1;

    for ( i = 1; i <= exp; ++i )
      result *= num;

    return ( result );
  }

Function definitions can appear in any order and in more than one source file as long as no function is split across files.

The variables defined in a function are local to that function only and cannot be referenced elsewhere in the code.

The compiler must know about functions prior to them being referenced - therefore either functions must precede their use in the code or function prototypes must be defined.