Functions

Building your Program even Further

    Introduction

    While we have come a long way from the Hello World, there is one major thing we need to cover to take the C tutorials to another level. And that is creating our own functions. While we have only coded within the int main function; it would be impractical for larger programs, as creating functions allows you to write a block of code and it may be executed as many times as you want. So creating your own functions to use in your own program is the most important task you will face, as it not only means you have to be more careful about how you code; it will bring more organisational skills with the way you work. It also brings in something you have not approached yet; program structuring. This will come in time beginning with this tutorial providing the first steps, as most of the basic points of learning C have been covered before, so you should know how things work by now. If not, go back and look on what you do not understand. In time, you will see the advantage with using functions, and the best thing for you to learn is to understand the modular side of coding, which will come in good stead in future, more sophisticated programming. Not only in C, but also a whole myriad of other programming languages.

    Understanding How Functions Work

    Functions are also known as Methods, Sub-Routines, and Procedures. As it has many facets to what they can do within a program. We are going to cover a few of those facets, which are commonly deployed in a C Program. First we will recap what we know so far from these programs. In the Hello World example, you may remember that it covered the int main entry point function. And when the program exits, it returns zero as it exited from the program successfully. Otherwise, if there was an error, the program would return any other number (in most cases any negative value). That is because it is a function, which should only return an Integer value. You can call a function anywhere within the main program scope (int main), as long as it is declared beforehand.

     return_data_type  function_name  (arg_param_type  arg_p, ....)

    Above shows a basic explanation of the structure of a function. First return_data_type, which the data type which will be used to return a value at the end of the function. function_name is the identifier name you will call the function by. Inside the parenthesis you can see arg_param_type, which is the data type each argument parameters you will assign to the function and arg_p, which is the identifier for the argument; no different to declaring a normal variable. You can use them as many times as you wish. The function always starts and finishes within a curly bracket scope.

    Now we are going to go straight in the deep end by looking at some example functions and their simple usages, some are different usages due to different data types.

    	void PrintingLine()
    	{
    		printf("Printing the Line");
    	}
    

    You can see that the return data type is a plain void; hence the lack of a return keyword, which basically does not return anything. There are no argument parameters being passed inside the parenthesis. You can do that if you wish. Say if you want to pass an integer value into parameter, that can be achieved. In this case we will only use one, which can be done like this snippet below.

    	void PrintingNumber(int num)
    	{
    		printf("Your number Selected %d", num);
    	}
    

    As mentioned with int main, the key feature of a function is the ability of returning data values. There are two ways to do it, and that is by return the value as in int main, or by simply passing through the argument parameter using a Reference (The Ampersand & sign mentioned in Simple Input Output article). Pass By Reference can be declared inside a argument parameter, which in turn allows the function to set a value like these brief examples show.

    	//Function Definition
    	void VolumeOfBox(int &assignvalue)
    	{
    		int width = 10;
    		int height = 20;
    		int depth = 40;
    		assignvalue = width * height * depth;
    	}
    

    The function example shows you pass a integer variable into the reference argument parameter; then inside the function's scope, the values will be set for the box's dimensions. Then the calculations will be assigned to the assignvalue data type. The usage example for this function below explains how it is deployed in code. The argument which you pass through can be described as a reference the integer being used in the argument parameter. So assignvalue is simply being used as a reference to boxdimension variable in the code.

    	int boxdimension;
    	VolumeOfBox(boxdimension);
    
    	printf("Box volume is %d",boxdimension);
    

    Now we will do another function doing the same task, which will return an integer instead.

    	int VolumeOfBox()
    	{
    		int assignvalue;
    		int width = 10;
    		int height = 20;
    		int depth = 40;
    		assignvalue = width * height * depth;
    		return assignvalue;
    	}
    
    	int boxdimension = VolumeOfBox();
    
    	printf("Box volume is %d",boxdimension);
    

    It shows the two ways of returning a data value to a assigned variable. They may be two different ways of doing it, but it does the same task. That is the best thing with C, so flexible in the way you can do things.

    Many times, writing a returning value function can be too much in some circumstances; especially when you do tiny computational tasks. Calling functions creates overhead within the program, as you are generating code to call the function. So the best approach for small tasks would be to use a inline function, which treats it as an inline expansion; therefore uses the code within a function as if it is copying and pasting a piece of code (inline), rather than a full blown function. So when you build the program, the compiler will treat it as if it is a normal segment of code, rather than a function. This is best used for simple few lines of code, otherwise there is a caveat, which is that it treads the code as if it is copied and pasted, so it will over-bloat the size of the program, but help performance a tiny bit. So keep in small doses only when necessary.

    	inline int ReturnNumber()
    	{
    		return 200;
    	}
    

    Example Code In Detail

    We will do a simple program, which will use new custom made functions, and use them for different tasks. In this program, it uses many elements from previous tutorials, but this time with extra custom made functions. The main task of this program is to take the user's gender and age. The program will then calculate the user's age, and by using and the UK retirement age based on gender (male is 65, female 60). It was meant to be simple code to understand, only so you can follow it. First we will declare the functions and variable identifiers we will use later.

    	// DECLARING FUNCTIONS BEFORE USE
    	void BeginProcedure();
    	int EnterAge();
    	void PrintsEndMessage(int _age, int _gender);
    
    	// DECLARE GLOBAL VARIABLE IDENTIFIERS
    	int user_age;
    	int user_gender;
    

    Now we will create the first function which is BeginProcedure; as you may have notice it returns void and does not take any argument parameters, As all the processing of this function will be done internally within its scope. BeginProcedure begins by declaring the local variables enter_char and user_gender. The value assigned to user_gender is minus one, to make sure that the following loop can run.

    	// THIS IS THE FIRST FUNCTION TO BE CALLED, IT SIMPLY 
    	// COLLECTS USER INPUT TO CONFIRM GENDER
    	void BeginProcedure()
    	{
    		char enter_char;
    		user_gender = -1;	//DEFAULT VALUE
    

    Inside BeginProcedure, we enter a do loop that will stay active until the user_gender has been assigned either value zero or one. Values are set when user either enters M or F, as doing this assigns zero or one respectively.

    		do
    		{
    			printf("Are You [M]ale or [F]emale, Enter Key to Confirm and Enter ");
    
    			//WAIT FOR THE USER TO ENTER INPUT
    			enter_char = getchar();
    
    			// THE INPUT WILL BE USED SORT IF M OR F WHERE ENTERED
    			// IF SO, IT WILL ASSIGN THE GENDER VALUE
    			switch(enter_char)
    			{
    			case 'm':
    			case 'M':
    				user_gender = 0;
    				break;
    			case 'f':
    			case 'F':
    				user_gender = 1;
    				break;
    			};
    
    			fflush(stdin);
    		}while(user_gender < 0 || user_gender > 1); // KEEPS LOOP GOING UNTIL GENDER IS SELECTED
    	}
    

    Now BeginProcedure has finished, we create EnterAge,which returns an integer, but again does not take any arguments. The main local variable _age, which its value will be used to return. Again the loop will run until the right value is entered into _age (From between 0 to 59 years). Then it will return the entered value.

    // MAKING SURE THAT THIS FUNCTION RETURNS THE CORRECT AGE ENTERED BY THE USER
    int EnterAge()
    {
    	int _age = -1;
    
    	do
    	{
    		printf("What is Your Present Age (0 to 59)? ");
    		scanf("%d", &_age);
    	}while(_age < 0 || _age >= 60); // LOOP WILL CONTINUE UNTIL RIGHT AGE IS ENTERED
    
    	return _age;
    }
    

    With that, we need to calculate and display the data needed so.

    	// NOT ONLY CALCULATES DATA, IT PRINTS IT...
    	void PrintsEndMessage(int _age, int _gender)
    	{
    		// RETIREMENT AGE WILL BE CALCULATED WITH THE TERNARY OPERATOR 
    		// ASSIGNING THE RETIREMENT AGE VALUE BASED ON THE GENDER VALUE
    		// AND SUBTRACTING THAT BY USER'S AGE
    		int retirement_age = ((_gender == 0)?65:60) - _age;
    
    		// FINALLY THE OUTPUT
    		printf("You are %d years away from the Current UK retirement age", retirement_age);
    	}
    

    As the functions have been declared before int main, we can call them within int main, as shown below. We could have build this program by not declaring functions, but only if the function definitions are coded before the int main, which will use these functions; otherwise, it will show errors (the functions will be undefined). Remember, either declare or define the functions before calling them inside code. Even though in the source code, this comes up before the functions we have created. I left this last, so we can dissect and put together the inner working of the code at implementation level.

    	// MAKING SURE INT MAIN BEGINS THE CODE
    	int main()
    	{
    		BeginProcedure();
    		user_age = EnterAge();
    		PrintsEndMessage(user_age, user_gender);
    
    		fflush(stdin);
    		getchar();
    		return 0;
    	}
    

    You can see in int main, BeginProcedure is the first function to be executed when the program runs. So this function will prompt the user to input the requested data first. Within this function, the variable user_gender will be assigned a value according to the gender of the user. Then when that is done, we use the EnterAge function which will return the user's age which will be input in like the previous entry. As you can see in the code example, the return value will be assigned to the user_age variable. The next function PrintsEndMessage will accept two different argument parameters. The first argument will accept the user_age variable and will use it to get the age passed into the calculations and output. The second argument will accept the user_gender variable and the function will output the data.

    Summary

    Now you have the main idea of how functions work inside a C program code, you can proceed by creating a few custom functions for yourself within the code project included within this article. You can do it; just getting used to it will make it easier and feel more natural. If you are to proceed with programming in this language; you will have to get used to it sooner or later.

    /*
    	USING FUNCTIONS	ReliantCode
    	Creating and Using Our Own Functions
    */
    
    #include <stdio.h>
    
    // DECLARING FUNCTIONS BEFORE USE
    void BeginProcedure();
    int EnterAge();
    void PrintsEndMessage(int _age, int _gender);
    
    // DECLARE GLOBAL VARIABLE IDENTIFIERS
    int user_age;
    int user_gender;
    
    // MAKING SURE INT MAIN BEGINS THE CODE
    int main()
    {
    	BeginProcedure();
    	user_age = EnterAge();
    	PrintsEndMessage(user_age, user_gender);
    
    	fflush(stdin);
    	getchar();
    	return 0;
    }
    
    // THIS IS THE FIRST FUNCTION TO BE CALLED, IT SIMPLY 
    // COLLECTS USER INPUT TO CONFIRM GENDER
    void BeginProcedure()
    {
    	char enter_char;
    	user_gender = -1;	//DEFAULT VALUE
    
    	do
    	{
    		printf("Are You [M]ale or [F]emale, Enter Key to Confirm and Enter ");
    
    		//WAIT FOR THE USER TO ENTER INPUT
    		enter_char = getchar();
    
    		// THE INPUT WILL BE USED SORT IF M OR F WHERE ENTERED
    		// IF SO, IT WILL ASSIGN THE GENDER VALUE
    		switch(enter_char)
    		{
    		case 'm':
    		case 'M':
    			user_gender = 0;
    			break;
    		case 'f':
    		case 'F':
    			user_gender = 1;
    			break;
    		};
    
    		fflush(stdin);
    	}while(user_gender < 0 || user_gender > 1); // KEEPS LOOP GOING UNTIL GENDER IS SELECTED
    }
    
    // MAKING SURE THAT THIS FUNCTION RETURNS THE CORRECT AGE ENTERED BY THE USER
    int EnterAge()
    {
    	int _age = -1;
    
    	do
    	{
    		printf("What is Your Present Age (0 to 59)? ");
    		scanf("%d",&_age);
    	}while(_age < 0 || _age >= 60); // LOOP WILL CONTINUE UNTIL RIGHT AGE IS ENTERED
    
    	return _age;
    }
    
    // NOT ONLY CALCULATES DATA, IT PRINTS IT...
    void PrintsEndMessage(int _age, int _gender)
    {
    	// RETIREMENT AGE WILL BE CALCULATED WITH THE TERNARY OPERATOR 
    	// ASSIGNING THE RETIREMENT AGE VALUE BASED ON THE GENDER VALUE
    	// AND SUBTRACTING THAT BY USER'S AGE
    	int retirement_age = ((_gender == 0)?65:60) - _age;
    
    	// FINALLY THE OUTPUT
    	printf("You are %d years away from the Current UK retirement age", retirement_age);
    }
    
    blog comments powered by Disqus
    Download Files Here

    PDF Version Here

    Download this Article in PDF

    Feedback on Article

    Report Bugs, Errors or Send Feedback

    MD5 Hash Check : What is MD5?