How to Declare a Function in C

Functions in C are the key to manageable structured programming. Every good program is written by taking the task and dividing it up into pieces, each of which becomes a function.

Instructions

  1. Create the Function Declaration

    • 1

      Create a unique name which says clearly what the function does. Use verbs in the name to emphasize the action. Use a consistent format, such as underscores (e.g., "calculate_subtotal") or inner capitalization (e.g., "CalculateSubtotal"). Avoid names that are too generic. For instance, "calculate_GPA_subtotal" might be better, since different things may be subtotalled.

    • 2

      Use functions to return a single value of built-in C datatype (including pointers). Functions that don't return anything will be declared as void.

    • 3

      Choose the function's parameters and their types. Pass exactly what the function needs to be do its job, no more and no less. Functions which don't need anything will use void.

    • 4

      Realize that most parameters are "passed by value." The function doesn't get the actual variable, only its value, and can change it without affecting the source. If you need to "pass by reference" to allow the function to change the value in the original variable, you must use pointers for the parameters.

    • 5

      Declare the function declaration like this:

      int calculate_GPA_subtotal(short studenttype, int *scores) {
      The declaration starts with the return type, then its name, then the parameters inside parentheses. Here's what it would look like for a function that has neither:
      void reset_printer(void) {
    • 6

      Include an abbreviated declaration. At the top of the C program file, or better yet in a header (.h) file, include an abbreviated declaration which omits the body, like this:

      int calculate_GPA_subtotal(short studenttype, int *scores); 
      void reset_printer(void);
      . Note that you can leave out the parameter names if you like, though it's good form to include them.

    Write the Function Body

    • 7

      Use {}. Function definitions end with a { which starts the body of the function and continues until the matching }. Use indentation to make the scope clear.

    • 8

      Use the return command to return a value. For void functions, use it without a value to jump out of the function from the middle.

Tips & Warnings

  • Declare functions with a single, clear purpose.

  • Functions should be as independent as possible, only interacting with the rest of the program through the values and variables passed to them, and their return values.

  • A function that is more than one or two screens high is probably too big. Consider splitting it into several functions.

  • If you must have your function have a "side effect" by modifying something global, declare this clearly in the comments.

Related Searches:

Comments

You May Also Like

Related Ads

Featured