A function is a group of statements (i.e. block of code) that perform a task. Every C program has at least one function called the main where program execution begins. Additional functions are created for numerous reasons:
- Organize, or modularize, the program
- Facilitate code re-use, i.e. write-once, run many
- Improved program/code readability
- Breaking a large project into smaller ones and assigning parts to teams
- Easier debugging
There are a few important things to know about C functions:
- Function name - every function is given a name
- Function declaration - informs the compiler about the function's name, return type, and parameters
- Function definition - the function body, i.e. statements to be executed/run
- Function call - the code that calls (runs) the function
- Return type - function may return a value. The return type is the data type of the value the function returns. If a function does not return a value then the return type is void
- Parameter - functions may have parameters (i.e. optional). They are are any data passed to it
- Function body - synonymous with function definition
- Recursion - when a function calls itself
Example: C that does not return anything
#include <stdio.h>
void greeting()
{
printf("Welcome.\n");
printf("This is a C program.\n");
printf("I hope you enjoy.");
}
int main()
{
greeting(); /* function call */
return 0;
}
Output:
Welcome.
This is a C program.
I hope you enjoy.
Example: Simple Function in C - returns an integer
#include <stdio.h>
int sq(int num);
int main() {
/* calling foo from main */
printf("2 squared = %d", sq(2));
}
int sq(int num) {
return num * num;
}
Output:
2 squared = 4
Example: Simple Function in C - returns an integer
#include <stdio.h>
/* function declaration */
int min(int num1, int num2);
int main () {
/* local variable declations */
int a = 23;
int b = 15;
int answer;
answer = min(a, b); /* function call */
printf( "Minimum value is : %d\n", answer );
return 0;
}
int min(int num1, int num2) {
int answer;
if (num1 < num2)
answer = num1;
else
answer = num2;
return answer;
}
Output:
15
Example: Simple Function in C - returns nothing (void)
#include <stdio.h>
void greeting(int count); /* function prototype */
main()
{
greeting(4);
}
void greeting(int count)
{
int x;
for(x = 0; x < count; x++)
printf("Welcome.\n");
}
Output:
Welcome.
Welcome.
Welcome.
Welcome.
Example: Recursion Example - Calculate Factorial
#include <stdio.h>
int recurs(int);
main()
{
int x, fact ;
printf("Enter number to calculate factorial: ");
scanf ("%d", &x);
fact = recurs(x);
printf ("Factorial value: %d", fact);
}
int recurs (int x)
{
int fact;
if (x == 1)
return (1);
else
fact = x * recurs (x - 1) ;
return (fact) ;
}
Output: (4 is user input, 24 is output)
Enter number to calculate factorial: 4
Factorial value: 24