Functions in C programming

Functions in C programming language are important when you find yourself writing the same lines of code over and over again. You can group those lines of code into a function that performs a certain task and call the function every time you need the task performed. A function (a procedure or a subroutine) allows us to perform some complex procedures in a single operation. A function is a group of statements that perform a certain task. In C, every program has at least one function (called main()).

Function definitions

Syntax:

     return_type function_name( parameters ){
     function body;
     return return_type_value;
}

The part outside the braces is the function declaration. The braces and their contents are the function body. Let us look at the parts of a function:

Function return type

The return_type is the data type of the value returned by the function. However some functions do not return anything, but instead they perform only the desired operations. Such functions have the return_type void.
Let us look at examples of functions with different return types:

#include <stdio.h>

// function that returns int type
int getAge(){
	return 33;
	}

// function that returns char type
char getGrade(){
	return 'A';
	}

// function that returns float type
float getBalance(){
	return 33.00;
	}

// function that returns double type
double avogadroNumber(){
	return 6.022e+23;
	}
	
// function that returns nothing
void bye(){
	printf("The end.");
	}

// main function
int main(){
	
	// let us call the functions
	
	printf("%d\n", getAge());            //> 33
	printf("%c\n", getGrade());          //> A
	printf("%f\n", getBalance());        //> 33.000000 
	printf("%lf\n", avogadroNumber());   //> 602200000000000027262976.000000
	bye();                               //> The end.
	
	return 0;
	
}
  • int getAge() function returns an int type value when called anywhere like this: getAge().
  • the same happens for each of the next functions. Each function should return its compatible type.
  • void bye() function is a void function, which ,means it has no return type. In this case, it only prints a string.

Function Parameters and Arguments

A function parameters are placeholders for data that is taken in by the function. When a function is invoked, if the function requires parameters, you pass in values to the parameters. The values passed in to the parameters are called arguments. For example:

#include <stdio.h>

// int is the return type
// getAge is the function name
// birthYear and currentYear are function parameters
int getAge(int birthYear, int currentYear){
	
	//return value type is int
	return currentYear - birthYear;
	}

int main(){
	
	// declare variables to hold data
	int bYear;
	int cYear;
	int age;
	
	// Prompt the user to enter input and get the input
	printf("Enter the birth year: \n");
	scanf("%d", &bYear);
	
	printf("Enter current year: \n");
	scanf("%d", &cYear);
	
	// call the function and assign the return value to variable age
	// pass in bYear and cYear as arguments
	age = getAge(bYear, cYear);
	
	// print the result
	
	printf("Your age is %d years", age);
	
	return 0;
}

Function declarations

A function declaration tells the compiler about a function name and how to call the function. The function body can either be defined separately or with together with the declaration.

Function declaration syntax


   return_type function_name(parameters);

For example:

#include <stdio.h>

// function declaration of getAge() function
int getAge(int birthYear, int currentYear);

int main(){
	
	// declare variables to hold data
	int bYear;
	int cYear;
	int age;
	
	// Prompt the user to enter input and get the input
	printf("Enter the birth year: \n");
	scanf("%d", &bYear);
	
	printf("Enter current year: \n");
	scanf("%d", &cYear);
	
	// call the function and assign the return value to variable age
	// pass in bYear and cYear as arguments
	age = getAge(bYear, cYear);
	
	// print the result
	
	printf("Your age is %d years", age);
	
	return 0;
}

// function definition of getAge() function
int getAge(int birthYear, int currentYear){
	
	//return value type is int
	return currentYear - birthYear;
	}

In the example above, the function declaration is as follows:

int getAge(int birthYear, int currentYear);

In function a function declaration, parameter names are not important, only their type is required, so the following code is also valid:

#include <stdio.h>

// function declaration of getAge() function
int getAge(int, int);

int main(){
	
	// declare variables to hold data
	int bYear;
	int cYear;
	int age;
	
	// Prompt the user to enter input and get the input
	printf("Enter the birth year: \n");
	scanf("%d", &bYear);
	
	printf("Enter current year: \n");
	scanf("%d", &cYear);
	
	// call the function and assign the return value to variable age
	// pass in bYear and cYear as arguments
	age = getAge(bYear, cYear);
	
	// print the result
	
	printf("Your age is %d years", age);
	
	return 0;
}

// function definition of getAge() function
int getAge(int birthYear, int currentYear){
	
	//return value type is int
	return currentYear - birthYear;
	}

The function declaration is required when you define a function in a different file from where you are calling that function or when you want to define the function below the main() function, as shown in the examples above. The function declaration is always placed above the main() function.

Calling a function

To use a function, you have to call that function to perform the defined task. To call a function, you simply need to write the function name and pass the required parameters (if any are required). If the function returns a value you can store the returned value in a variable. For example:

#include <stdio.h>

// function definition
int isEven(int inputNumber){
	// return the remainder of dividing the input number by 2
	// if the input is even, it returns 0, and if odd it returns 1
	return inputNumber % 2;
	}

	
int main(){
	
	// calling the function and assigning the result to variable a
	// variable a should be int because the function returns int
	int a = isEven(24);
	
	// we can then print the returned value as follows
	
	printf("%d", a);     //> 0
	
	return 0;
	
}

Let us see another example, this time we call a void function:

#include <stdio.h>

// void function definition
void myAge(int Age){
	
	// void function has no return statement
	// it returns nothing
	printf("I m a %d years old", Age);
	}

	
int main(){
	
	// calling the function
	myAge(23);                   //> I m a 23 years old
	
	return 0;
	
}

For a void function, there is no result to store because it doesn’t return anything.

When a function is called by a program, the program execution control is transferred to the called function. The called function then performs its defined task until a return statement is met or the function closing brace is reached.

When the return statement is executed the statement returns the designated value and program control is immediately passed back to the calling program. For example:

#include <stdio.h>

int testReturn(){
	printf("Execution passed to the testReturn function. \n");
	printf("Inside the function, before the return statement. \n");
	return 1;
	printf("Inside the function, after the return statement. \n");
	}
	
int main(){
	
	
	printf("Before function is called. \n");
	testReturn();
	printf("Control is passed back to main.");
	
	return 0;
}

/** Output **
Before function is called. 
Execution passed to the testReturn function. 
Inside the function, before the return statement. 
Control is passed back to main.
**/

Here is how the above program works:

  • execution starts in the main() function and "Before function is called." is printed.
  • testReturn() is called and the first statement of the function is executed, printing "Execution passed to the testReturn function."
  • the second statement of the function is called and it prints " Inside the function, before the return statement."
  • the return statement is executed passing the control back to the calling program before the last statement is reached. Which means the last statement of the function is never executed.

Call by Value

Call by value method copies the value of an argument into a function variable. A copy of the value is created inside the function, which means that changes made to the parameter inside the function do not reflect on the actual argument. In short, the code within a function cannot alter the value arguments used to call the function.

For example:

#include <stdio.h>

void halveNumber(int num){
	num = num/2;
	}

int main(){
	
	int num = 24;
	
	printf("Initial value of num is %d\n", num);
	
	halveNumber(num);
	
	printf("Final value of num is %d\n", num);
	
	return 0;
}

/** Output **
Initial value of num is 24
Final value of num is 24
**/

The final value of num is still 24 even though halveNumber() was called. The reason is because the function halveNumber() acted on a copy of num and not on the actual num.


Call by Reference

Call by reference method copies the address of an argument into
the parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the function parameter affect the argument passed in.

To pass values by reference, argument pointers are passed to the function. The function parameters are declared as pointer types as in the function that point to the addresses of the variables.

#include <stdio.h>

void halveNumber(int *num){
	*num = *num/2;
	}

int main(){
	
	int num = 24;
	
	printf("Initial value of num is %d\n", num);
	
	halveNumber(&num);
	
	printf("Final value of num is %d\n", num);
	
	return 0;
}

/** Output **
Initial value of num is 24
Final value of num is 12
**/