C++ Functions And Their Uses In C++ Programs

c++ functions

Table of Contents

Description:

c++ functions-this is a very detail tutorial about function and their using in c++ programming and some information about c++ variable.

c++ functions  Introduction:

As programs get longer and become more complex they become harder to understand. For this reason, all computer languages contain modular programming techniques that facilitate the design implementation and operation of large programs. This tutorial introduces the idea of modular programming which breaks up a long program into smaller parts each of which is more manageable.

There are basically two types of functions

  • Library functions
  • User-defined functions

We are already familiar with the library function. These are pre-defined functions which are accessed through header files. For example we have used <iostream.h> for I/O functions similarly we used <math.h> for mathematical functions. In addition to providing the library functions, c/c++ also contains a feature by which may define your own c++ functions. These functions can be referenced in any part of your program just as the library functions are referenced.



What is a C++ Function:

A C++ function is a subprogram or module to which any amount of data can be sent but which returns only one value. c++ functions are used to perform some logically isolated tasks.it makes it easier to write programs and keep track of what they are doing. It avoids rewriting the same series of instructions over and over. These instructions are written once but are used at several places in the main program as and when desired. Thus functions are not just for storage saving they also provide us a way of breaking the program into separate short and well-defined tasks that may easily be designed debugged modified and documented. Every c/c++ program has at least one function main() which is automatically called when you execute the c/c++ program i.e program execution always begins with main() the main() function may call other c++ function which in turn call still other functions.

Each c++ functions has its own name and when that name is encountered the function gets called i.e the control is transferred to the first statement in the called function. The c++ functions is completed when it executes the last statement in the function or it executes a return statement. The general format is as follows:

return(expression);

where the expression is optional if the expression is omitted the return statement simply causes control to transfer back to calling the function without any information transfer. The expression returned need not be enclosed in parentheses. A few valid examples of return statements are given below:

return 3;

return(x*x*x);

return(func());

when the computer executes the return statement the expression following the return is returned as the function to main() or call function. So the control is transferred to the called function body when the name of the function Is encountered whereas in function subprogram the return statement transfers the control back to the main() or calling the function at the line after the function call. This is illustrated in the following program example:


example: how to call a function in c/c++

The function used in the above program is known as a subroutine. A subroutine is a function that does not return any values

Declaring c++ functions:

Before defining a function you must first declare a function. A function cannot be called until & unless being declared this declaration of a function is called its prototype which consists of functions return type function name and parameter list and ends with a semicolon. You can define a function before using it. In this case, there is no need for a function prototype. But, it is not considered a good programming practice for many reasons, therefore always avoid it.

C++ FUNCTION PROTOTYPE

 The function prototype is a statement, which must end with a semicolon. As discussed earlier, function prototype consists of function’s return type, function name and the number and type of its parameters. It has the following general format:

return_type function_name ( type parameter, type parameter, ……..);

For example; in the above example, the function prototype being used is:

void Funct();

in which, the function’s return type is void. If a function does not return a value, its return type will be void. i.e. void type specifies the empty set. Similarly, a function that has no parameter can use the reserved word void in its parameter list, like,

void Funct(void);

 Any valid identifier’s name can be used as a function’s name i.e. it must follow the naming rules for identifiers. Always choose those names which import some meaning. For example:

void Message();

int Cube{ int x);

Each function name follows the parameter list, enclosed in parentheses. The parameter list consists of parameters and their types, separated by commas. Many functions are not required to have parameters (as in the above example), an optional void may be used here as:

void Funct(void);

Consider another example:

 float Area(int length, int width);

Parameter names are optional in the parameter list. It would be sufficient to mention their types only; like:

 float Area(int, int);

 However, it is recommended to add parameter names in the parameter list for prototype


DEFINING The C++ FUNCTIONS

Like main(), the function definition is a complete function, consisting of a function header and function body, which may appear anywhere outside the main() function. The function header must be exactly the same as the function prototype, except no semicolon is used at the end of the definition and second, it is necessary to mention the parameter names in the parameter list (if any). The function body consists of a statement or group of statements, enclosed within a block of braces. There is no semicolon after the closing brace, but all statements within the body of the function must be terminated with a semicolon. The return statement is used at the end of the function to return a value. The return statement is not required for every function, but it is strongly recommended to always include it in your function subprogram. The general format of the function definition
is:
return_type function_name ( type parameter, type parameter, ……..)

{
body of the function;

}

example: c++ functions that returns no value

Calling the C++ Functions:

 Executing the statements of a function to perform a task is called calling of the function.

A function is called by referencing its name. The parameters (if any) of the function are given in parentheses after the name of the function. If a function has no parameters then the parentheses are left blank.

 If a function has a return value of numeric type then it can be used or called in an arithmetic expression. When a function is called the control shifts to the function definition and the statements in the body of the function are executed. After executing the statements in the body of the function, the control returns to the calling function and the next statement that comes immediately after the function call statement is executed.

Example: using a C++ functions print a message on the screen

A function is written once but may be used at several places in a program as and when desired. For example:

 Example: c++ functions that calls more than one time in the program.

A function can be called from any other function or any function can call any other function. For example:

The default return type is int. If one is not explicitly designated, the return type will be int. Consider the following two programs, the first one with the data type, while the other is not.



Types of functions in c++:

Passing arguments to functions:

Any number of values can be passed to a function being called, but the type order and number must be similar to the function definition. A value that is supplied to a function when it is called is known as an argument. For each argument passed to a function, a variable must be provided in the function definition to hold that value. Such variables are called parameters.

 In general, the values in the invoking function are called Arguments, while the corresponding variables in the invoked function are called parameters. When a Function is called, the arguments are placed inside the parentheses after the name of the function like Sum(a,b,c). When the function is invoked, the arguments hand over the  data to the parameters.

Arguments are also called as actual arguments or actual parameters, whereas the parameters are often called dummy arguments, dummy parameters or formal parameters, because they have no values. In a sense, they do not exist. When values of all the arguments are passed to the parameters, they come into being.

 Parameter names may be different from arguments. However the same name may also be used. but since compiler treats them as different variables, therefore. mostly different names are used. Thus it means that the position of the variable in the parameter list is important, not their names.

c++ functions

example:  write a program which pass value as arguments in c++ functions

example:  write a program which pass value as arguments and find the cube of the number  in c++ functions

example:  write a program which pass value as arguments and Find the 7!/2!3!  factorial in c++ functions


Write a program to pass a number as arguments to the function body Print the table of that number in the c++ functions body

Example: Write a program which takes three arguments first is numeric number second is the arithmetic operator and the third is also the numeric number by using switch case statement select the operator and perform some operation.

Passing Arrays as Arguments to a c++ Functions

 An array variable can also be passed to the function as an argument when an array is passed to the  c++ function only the starting address of the array is passed to the function. The C++ does not make a separate copy of array in the body of the function it only assigns the starting address of the same memory area of the array to the array name used in the declarator of the function. The function  can change the contents of the array by directly accessing the memory cells where the array’s elements are stored. Thus, although the starting address of the array is passed, the elements of the array can be changed as if they have been passed to the function.

Declaration of a c++ Functions with Array Arguments

When an array variable is used as an argument of a function, it is mentioned in the function declaration For example, if a function is to use two arrays as arguments, one of float type one-dimensional array and the other of integer type one- dimensional array, it is declared as:

 void max (float[], int[] );

 If two-dimensional arrays are to be used as arguments, two square brackets are used as shown below: void temp (float[] [], int[] []);


C++ Function Definition with Array Arguments

The name of the array and its type is given in declarator of the function definition. The type of the array in declarator must correspond with its type given in the prototype of the function. For example, the function definition with array arguments is written

void max (float xy [], int ab [])

{

 body of the function

}

 The size of the array can be given both in the function declaration and in the function definition but its use is optional.

Calling c++ Functions with Array Arguments

When a function that uses an array as argument is called, then only the name of the array without subscripts is given. This is because only the memory address of the array is passed to the function. The data is accessed from the same memory location. The name of the array used in the function definition and in the function call may be different or same. Because, it is the name of the array in the function definition to which the address of the array is passed.

Example: write a program to find a number and its location in the array using a function.

Example: Find the maximum number in the  array using C++ function

passing Structures to c++ Functions

The structures can also be passed as arguments to a function. If a structure is to be passed to a c++ function, then it must be defined before the declaration of the function that uses the structure type data as an argument. The program example given below explains the use of structure type data as an argument of a function.

Example: write a program which pass the structure value as an argument in c++ function

The variable s1 is declared as structure type (i.e. xyz) inside the main function and the function “rec” is declared after this. The function “rec” uses an argument of type “xyz”, i.e. of structure type. The function “rec” is called by passing the structure variable s1 to function definition “rec”.

In function definition, the variable “fs” of type “xyz” receives the data of s1 and the same is printed on the screen. An array of structure type can also be passed as argument to & function in the similar way as any other array is passed as argument.



Returning Data From c++ Functions :

A function can return only one value. It can be of any type except sinng and array. The type of data that a user-defined function returns is declared in function declaration. The value or data is returned from the function to the calling function by the “return” statement

 Return Statement

The “return” statement is used to return the calculated value from function definition to the calling function. In some compilers of C and C++, it is used as a last statement of body of the function to return the control as well as to return the calculated value to the calling function.

 Its syntax is:

return expression;

 where

expression represents an arithmetic expression or constant  value of the expression is returned to the calling function.

If the function has a “void” return data type, then the use of this statement is optional.

Declaration of  c++ Functions that Returns a Value

The type of a function specifies the type of the data returned by it. It is specified in the function declaration. It is also called the data type of the function. The data type of a function is declared in the same way as the type of a variable is declared, e.g.

float temp (void);

, In the above function declaration;

 temp   name of the function

float    returned data type

void    in the brackets specifies that it has no arguments

Calling a Function that Returns a Value

The function that returns a value can be called in an arithmetic Expression. In this case the function is treated as a variable. Similarly, the function may be assigned to a variable or it can be  directly sent to an output device. i.e. printer, screen or file,

 For example, to assign the returned value of the function “temp” to variable “r”. the statement is written as:

   r = temp() ;

where “r” is a variable that receives the returned value of function “temp”. Since the function will return float type value, the variable “r” should also be of float type.

 To print the returned value directly on the screen, the function “temp” is called as:

cout<<” The returned value is : ” <<temp();

To use the function in an arithmetic expression, it is called as:

r = x + temp () * 1000;

where

r represents the receiving data variable of numeric type.

x represents a variable of numeric type.

temp()  represents a function call. It is also treated as variable.


Function Definition that Returns a Value

The function that returns à value is defined in the similar way as other functions are defined but in the declarator the return data type is mentioned.

The returned data type must be the same as mentioned in the function declaration. The “return” statement must be used in the function body to return the value to the calling function.

Example: Write a program which converts kilogram into grams using user-defined c++ functions

Returning Structures from Functions

Since a structure type data can be passed to a function, a function can also return a structure type data. Usually, the structure type data returned by a function is assigned to a structure type variable. For example:

 In the above program, the “temp” is the tag name of structure. The function “abc” is declared that has no arguments and its returned data type is “temp” i.e. structure type. The variable “xyz” is also declared as of Structure type. When the function is called. then its returning data assigned to variable “xyz” after executing body of the function. In the function definition, the variable “rec” is also declared as data, type “temp”. The data is entered into the “rec” and the same is returned to the calling program by return statement.


LOCAL AND GLOBAL VARIABLES

The variables can be declared inside the main function. Inside user defined functions or outside the main function. The effect of the variables declared in these places is different. Based upon their effects, variables are divided into two classes:

  • Local variables
  • Global variables

Local Variables

The variables that are declared inside the main function or user-defined function are called local variables. These variables are called the automatic variables. The keyword “auto” can be used to declare these variables. For example,

 auto int a, b, c;

 The use of keyword “auto” is optional. The variables used inside the functions are automatic by default.

Life-Time of Local Variables

The lifetime of a variable is the time period between the creation and destruction of the variable. A variable remains available and can be used only during its lifetime. When the control is transferred to a function, the local variables or variables declared inside that function are automatically created and they occupy memory spaces to store data. When the control returns to the calling function or calling program, the variables of that function are destroyed and their data is lost. Thus local variables can only be accessed from within the function in which they are declared. They are not available outside that function. The following example explains the concept of local variable

In the above program, the variables a, b and s are declared in the main function. These are local variables for the main function. The variables declared in the “sum” function are x, y and rs. The variables declared in function declarator are also treated as local variables. When the function “sum” is called, control transfers to the function definition “sum”. The variables x, y and rs are created into the memory. the value 10 is stored in variable “x” and 100 in variable “y”. The sum of x and y is calculated inside the function definition and the result is return to the calling function. When the control returns, the variables x, y and rs  are destroyed from memory.

Global Variables

 The variables that are declared outside the main function or any called global variables or external variables. These variables can be accessed in any function at any time during the execution of  the program. The global variables are used e are used when variables are to be accessed by

more than one function in on in a program.



Life-Time of Global Variables

The global variables exist in the memory throughout the program execution. They are created into the memory when the program execution state they are destroyed only when the program ends. Therefore, the lifetime of the global variables is between the starting and the termination of the program

A program example is given that uses global as well as local variables.

In the above program, a, b and s variables are declared as global variables and are outside the main function. These can be accessed in the function sum (as defined above) as well as in the main function. The variables x and are local variables of function “sum”.

 STATIC VARIABLES

Static variables are special variables that are declared inside a function by using the keyword “static”. Like local variables, these can only be accessed in the function in which they are declared but they remain in existence for the lifetime of the program.

Another difference between local variables and static local variables is that the initialization in the static variables takes place only once when the function is called for the first time. A program example is given below that uses the static variables.

Note: The static global variables can also be declared outside the main function but these are normally used in multiple-file programs.


LOCAL AND GLOBAL FUNCTIONS

The functions that are declared inside the main function or inside any other function are called local functions. They can be called only in that function in which they are declared.

 The functions that are declared outside the main function are called global functions. They can be called by any c++  functions.

 The function prototypes defined in the header file are treated as global functions because they can be called in any function.

Recommended For You

Leave a Reply

%d bloggers like this: