Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Mail Systems
Eclipse Documentation

How To Guides
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Problem Solutions




2.4. Making your own Functions

In that last example we defined just one function. To add another function you must generally do two things. First you must define the function, just like we defined main(). Also you you must declare it. Declaring a function is like telling GCC to expect it, we didn't have to declare main() because it is a special function and GCC knows to expect it. The name, or identifier, you give to a function must appear in both the definition and the declaration.

Functions identifiers can be made up of the alphabetic characters "a"-"z" and "A"-"Z", the numeric characters "0"-"9" and the underscore character "_". These can be used in any order so long as the first character of the identifier is not a number. As we said earlier, C is case-sensitive so My_Function is completely different to my_function. A functions identifier must be unique. Identifiers can safely be up to 63 characters long or as short as 1 character.

Along with it's identifier you must give each function a type and a block of code. The type tells the compiler what sort of data it returns. The return value of a function can be ignored, printf() returns an integer saying how many character it displayed to the terminal. This information wasn't important to us so we ignored it in our program. In the next chapter we'll discuss types of data in detail, until then we'll gloss over return values.

Here's a program that defines three functions:

Example 2-3. three_functions.c

#include <stdio.h>

/* function declarations */
int first_function(void);
int goodbye(void);

main()            // function definition
  printf("the program begins...\n");

  return 0;

first_function()  // function definition
  /* this function does nothing */
  return 0;

goodbye()         // function definition
  printf("...and the program ends.\n");

  return 0;
In the above example we wrote first_function() which does nothing and goodbye() which displays a message. Functions must be declared before they can be called are called, in our case this means they must appear our definition of main(). In practice, function declarations are generally grouped at the top of a file after any #include lines and before any function definitions.

  Published under the terms of the GNU General Public License Design by Interspire