Functions 2025 2

Functions 2 #

In C programming, a function is a block of code that performs a specific task. The task is often a repetitive task that is used often. Functions enable code reuse which helps make programs easier to read, understand, maintain and debug.

In the previous seciton we explored the idea of what a function was, how to implement it and the benefits of using functions.

Some of the benefits of using functions are:-

  • Programs can become modular.
  • Programs are easier to read and more efficient.
  • Editing becomes easier so programs are easier to maintain.

.

We also explored the syntax of creating a function and that:

  1. A function can be passed variable (argument list).
  2. A function can return a variable.
  3. It is NOT a requirement that a function MUST be passed or return a variable.

Local vs Global Variables #

Before discussing the different ways to pass a variable to the function it is good to understand that there are two basic types of variables that we use, LOCAL and GLOBAL.

A LOCAL variable is one that is declared inside a function. The LOCAL variable will only exist inside that function.

int main(void){

int num;	// 'num' is a LOCAL Variable declared inside main().
... .. ...	// It will only exist INSIDE the main() function.
... .. ...
return 0;
}

.

The small example below shows two functions with variables delcared in each of them.

  • num is LOCAL to main
  • num1 is LOCAL to the function func1
  • num CANNOT be accessed inside the function func1 as it ONLY exists inside main
  • num1 CANNOT be accessed inside the function main as it ONLY exists inside func1
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
// LOCAL VARIABLES
int main()
{
	int num;// This is a local variable to main, called num.
			// The value stored in num can not be directly accessed in func1.
}


void func1(){
	int num1; //This is local variable to func1, called result1.
		 	 // The value stored in num1 can not be directly accessed in main.
}

.

A GLOBAL variable is one that is declared outside of functions. The GLOBAL variable will exist throughout the entire program.

#include <stdio.h>

int num;// 'num' is a GLOBAL Variable declared outside of any function.
	// It will exist throughout the entire program.

int main(void){

int num2;	// 'num2' is a LOCAL Variable declared inside main().
... .. ...	
... .. ...
return 0;
}

.

The small example below shows two functions with one GLOBAL variable.

  • num is a GLOBAL variable to the entire program.
  • ALL functions can access this global variable.
  • ‘Can you work out what the output of this program would be?’
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
// GLOBAL VARIABLES
#include <stdio.h>

void func1();	// Function Prototype -> Return Type is VOID so this function DOES NOT return a value.
		// The has NO argument list, therefore NO variables will be passed to it.

int num = 3;	//GLOBAL Variable

int main()
{	
	num = num + 2;	// 2 is added to the GLOBAL variable, num, and the result us stored in num.
	func1();	// The function is called. Notice that NO arguments are passed to it.
	return 0;	// Program ends
}

void func1()		//Function Definition
{
	num = num + 3;
	printf("num now = %d", num);
}

The term scope is often attributed to variables. Scope refers to the block or area in the program where a variable can be used or accessed. Outside of this block, the variable cannot be accessed and it will be seen as an undeclared identifer. A LOCAL and GLOBAL variable have different scopes as one is confined to the function in which it is declared (LOCAL) whereas the other can be accessed throughout the entire program (GLOBAL).

Passing Variables to a Function #

There are two methods that can be used to pass data to a function:

  1. PASS by VALUE
  2. PASS by REFERENCE

.

1. PASS BY VALUE #

When a variable is passed by VALUE the actual value of the variable (known as the actual parameter) is copied into another location (known as the formal parameter) and is passed to the function. Any changes made to the formal parameter do not get reflected in the actual parameter. Different memory locations are allocated for the actual and formal parameters.

.

The small example below shows two arguements being passed to a function.

  • num and num2 are LOCAL to main
  • They are both passed to the function called inc.
  • The function inc DOES NOT RETURN a value.
  • In the main()function the values of num and num2 will remain the same.
  • Even though they get increased in the funciton, inc, their actual values remain the same in the main() function.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
// PASSING VARIABLES BY VALUE
#include <stdio.h>

void inc(int num, int num2);	//Function Prototype

int main()
{	
    int num, num2;
    num = 3;
    num2 = 5;
    inc(num, num2);		//Passing 2 arguments by their value
    printf("num = %d", num);	//Num will still be 3
    printf("\nnum2 = %d", num2);//Num2 will still be 5
    return 0;
}

void inc(int num, int num2)		//Function Definition
{
	num = num + 2;			//This makes num = 5 BUT only inside this function
	num2 = num2 + 3;		//This makes num2 = 8 BUT only inside this function
}

.

NOTE: It should be noted that:

  1. The name of the arguments in the receiving function DO NOT have to be the same name as those coming from the passing function.
  2. The order in which the arguments are passed to the function is very important. The 1st argument passed will be copied into the 1st argument in the argument list of the function.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
// PASSING VARIABLES BY VALUE
#include <stdio.h>

void inc(int a, int b);	//Function Prototype

int main()
{	
    int num, num2;
    num = 3;
    num2 = 5;
    inc(num, num2);		//Passing 2 arguments by their value
    printf("num = %d", num);	//Num will still be 3
    printf("\nnum2 = %d", num2);//Num2 will still be 5
    return 0;
}

void inc(int a, int b)		//Function Definition. The value of num copies to a, num2 to b.
{
	a = a + 2;		//We now use the variables a and b inside the function.
	b = b + 3;		
}

.

2. PASS BY REFERENCE #

When a variable is passed by REFERENCE the *address (memory location) of the actual parameter is passed to the function. Now the variables in the passing function and the receiving function use the same address to acces the variable data. Any changes made to the variable in the function WILL be reflected in the passing function also.

.

The previous example has been modified to use PASS BY REFERENCE.

  • num and num2 are LOCAL to main
  • They are both passed to the function called inc using a reference to their memory location.
  • NOTE that the & is now used to indicate the address of the variable is passed
  • The function inc DOES NOT RETURN a value.
  • In the main()function the values of num and num2 will now be modified as they are modified in inc.
  • The values are modified by accessing the address of each variable. This is achieved using the * character.
  • Using the * means we are using a POINTER.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
// PASSING VARIABLES BY REFERENCE
#include <stdio.h>

void inc(int* num, int* num2);	//Function Prototype - num1 and num2 are now pointers to integers

int main()
{	
    int num, num2;
    num = 3;
    num2 = 5;
    inc(&num, &num2);		//Passing 2 arguments by a pointer to their location
    printf("num = %d", num);	//Num will still be 3
    printf("\nnum2 = %d", num2);//Num2 will still be 5
    return 0;
}

void inc(int *num, int *num2)		//Function Definition
{
	*num = *num + 2;		//This makes num = 5 both here and in main()
	*num2 = *num2 + 3;		//This makes num2 = 8 both here and in main()
}

Comparison of pass by VALUE Vs REFERENCE #

Pass By Value Pass by Reference
A copy of the value is passed to the function The address of the variable is passed to the function
Changes made to the variable inside the function are limited to the function Changes made inside the function are NOT limited to the function
The value of the actual does not change The value of the actual can be changed
Actual and formal parameters are created at different memory locations Actual and formal parameters use the same memory location
This is considered safer as the original data is preserved This is considered risky as it allows direct modification of the original data

.

Returning Values from the Function #

We already know that a function can return a value to the calling function. The returned value will depend on the data type that the function was declared with (int, double, char, etc).
The type of data being returned by the function and the return type sepcified in the function prototype MUST MATCH.

The general form of the function PROTOTYPE is:-

return_Type function_Name(parameter list);
double func1(int a, int b);	//The return type is **double** therefore the function must return data that is type double
				//The arguments PASSED to this function are both integers

We also know that a function DOES NOT have to return a value. If a function does NOT return a value we use the void key word.

We also know that a function DOES NOT have to be passed any arguments. If a function is NOT being passed any arguments we leave the () empty.

The general form of the function PROTOTYPE is:-

return_Type function_Name(parameter list);
void func1();	//This function has NO return type and NO argument list.
		// It will NOT return a value and it CANNOT be passed any values.

.

Final Note #

We have covered the very basics of using functions and their benefits. Functions are used throughout programming and it is a concept that needs to be understood. The final point about functions is that a function can call itself. This is known as *RECURSIVE. A recursive function is one that can call itself. A good example of a recursive function is one that is used to calculate the FACTORIAL of a number. See the example code below:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// RECURSIVE FUNCTION
#include <stdio.h> 

int fact (int num);	// Declaration of a function called fact
			// It will return an integer value and will be passed an integer value

int main() 
{ 
int n,f;		//LOCAL Variable declaration
 
printf("Enter the number whose factorial you want to calculate?"); 
scanf("%d",&n);
 
f = fact(n); // Call of the function, fact and pass it the value stored in n.

printf("factorial = %d",f); 
} 

int fact(int n)		// Definition of the function fact
{ 
	if (n == 0) 
	{ 
	return 1;	//Factorial of 0 = 1
	} 
	else if ( n == 1)
	{ 
	return 1;	//Factorial of 1 = 1
	} 
	else 
	{ 
	return n*fact(n-1); //Get the factorial of the number by calling itself
	} 
}