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
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com
Answertopia.com

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

  




 

 

The GNU C Programming Tutorial - Function examples

Node:Function examples, Next:, Previous:Function names, Up:Functions



Function examples

Here is an example of a function that adds two integers and prints the sum with C's "print formatted" function named printf, using the characters %d to specify integer output.

void add_two_numbers (int a, int b)               /* Add a and b */
{
  int c;

  c = a + b;
  printf ("%d\n", c);
}

The variables a and b are parameters passed in from outside the function. The code defines a, b, and c to be of type int, or integer.

The function above is not much use standing alone. Here is a main function that calls the add_two_numbers function:

int main()
{
  int var1, var2;

  var1 = 1;
  var2 = 53;

  add_two_numbers (var1, var2);
  add_two_numbers (1, 2);

  exit(0);
}

When these functions are incorporated into a C program, together they print the number 54, then they print the number 3, and then they stop.

 
 
  Published under free license. Design by Interspire