Learning C by Example (2015)
4. Functions
This chapter explains how to create function using C.
4.1 Creating Function
Declaring function in C can be written as follows
void foo(){
printf("foo() was called\n");
}
We put this function on above main() function. Then, we can call this function, for instance foo().
For illustration, we can create a file, called funcdemo.c , and write this code.
#include <stdio.h>
void foo(){
printf("foo() was called\n");
}
int main(int argc, const char* argv[]) {
foo();
return 0;
}
Save this file. Compile and run this program.
$ gcc -o funcdemo funcdemo.c
$ ./funcdemo
A sample of program output can be seen in Figure below.
We also can declare a function on below of main() function but we must declare our function name.
Add this code on funcdemo.c file.
#include <stdio.h>
// implicit declaration for functions
void boo();
int main(int argc, const char* argv[]) {
boo();
return 0;
}
void boo(){
printf("boo() was called\n");
}
If we compile and run this code, we will get a response, shown in Figure below.
4.2 Function with Parameters and Returning Value
You may want to create a function that has parameters and a return value. It is easy because you just call return into your function.
Add this code in funcdemo.c file. Write this code.
#include <stdio.h>
// implicit declaration for functions
int add(int a, int b);
int main(int argc, const char* argv[]) {
int result = add(10,5);
printf("result: %d\n",result);
return 0;
}
int add(int a, int b){
return a + b;
}
Try to compile and run this file.
4.3 Function with Array Parameters
We also can declare a function with array as parameters. To know how array size, our function should declare array size.
Write this code into your program for illustration.
#include <stdio.h>
// implicit declaration for functions
double mean(int numbers[],int size);
int main(int argc, const char* argv[]) {
int numbers[8] = {8,4,5,1,4,6,9,6};
double ret_mean = mean(numbers,8);
printf("mean: %.2f\n",ret_mean);
return 0;
}
double mean(int numbers[],int size){
int i, total;
double temp;
for (i = 0; i < size; ++i){
total += numbers[i];
}
temp = (double)total / (double)size;
return temp;
}
Now you can compile and run this program.
4.4 Function and Pointer
We can pass pointer as parameters in our function. For illustration, we can create swap() to swap our values.
Try to run this program.
#include <stdio.h>
// implicit declaration for functions
void swap(int *px, int *py);
int main(int argc, const char* argv[]) {
int *x, *y;
int a, b;
a = 10;
b = 5;
// set value
x = &a;
y = &b;
printf("value pointer x: %d \n",*x);
printf("value pointer y: %d \n",*y);
swap(x,y);
printf("swap()\n");
printf("value pointer x: %d \n",*x);
printf("value pointer y: %d \n",*y);
return 0;
}
void swap(int *px, int *py){
int temp;
// store pointer px value to temp
temp = *px;
// set pointer px by py value
*px = *py;
// set pointer py by temp value
*py = temp;
}
A sample of program output can be seen in Figure below.