A closer look at Functions


The following topics are covered in this section:


Default Arguments

While using functions with parameters, you can specify default argument values (i.e. in case arguments are not passed to the function then the function will assign the default values to the parameters).

The output will be:

If the programmer specifies arguments then the default arguments are not used. Some points to remember are:

void add (int var1=5, int var2)


Return Values

So far we have only seen functions with ‘void’ as the return data type. In this section you will learn about how to return values from functions. ‘void’ means that no value is returned by the function.

Return value, as the name suggests, is used to return some value from the function to the caller process. When a function completes its execution it can return a single value to the caller. ‘return’ serves two purposes:

The syntax is:

return variable-name;

This statement is specified at the end of the function body before the closing brace. When a function returns a value, the data type of the return value must be specified in the function header as well as in the function declaration.

Consider the following program that uses a function to return a value:

#include <iostream.h>
int add (int , int);                                         // Declaration
int main ( )
{
    int sum, var1, var2;
    cout<< "Enter the two numbers";
    cin>>var1>>var2;
    sum = add(var1,var2);                         //Function call
    cout<< "The sum of the two numbers is "<<sum;
    return 0;
}
int add(int num1, int num2)                     // Function Definition
{
    return num1 + num2;
}

In the above program the statement of interest to us is

sum = add(int num1, int num2);

The right side of the equal sign is actually the function call. This is being assigned to a variable called ‘sum’. Hence, the function ‘add’ has to be executed and some value should be returned. This returned value is assigned to ‘sum’.

In the function header instead of ‘void’ we have mentioned ‘int’ as the return data type. This means that the function ‘add’ will return (or give back) an integer quantity to the calling program (in this case the caller is the main ( ) function). Therefore, the sum of ‘num1’ and ‘num2’ will be returned to main ( ). You have to mention the return data type in the function declaration also.

Remember: The data type specified in the function declaration should match the return data type in the function definition. Make sure that the data type of the variable you are returning to (in the above case this is the variable ‘sum’) also belongs to the same type as the return data.

What would happen if you return a value from a function but don’t use it? Will it cause an error? What if you don’t assign the returned value to any variable? Is it a problem? It is entirely your choice as to whether you want to use a returned value. If you don’t assign the returned value to the variable then the compiler simply ignores the return value. It will not be stored anywhere unless you assign it to some variable.


Returning Void

Once a function returns a value, the function will terminate and program flow will be transferred back to the caller. When a function has a return data type of ‘void’ we needn’t specify the return statement at the end of the function body. The function will terminate at the end of the function body (i.e. when it encounters the closing brace of the function body). If you would like to use a return value in for a function that has void as the return data type, then you can type:

return;

No value is returned in this case to the caller but program flow is handed over back to the caller program when the ‘return;’ statement is encountered. The following program illustrates this concept of returning void from a function:

#include <iostream.h>
void convert(int dollar)
{
        if (dollar<0)
        {
            cout<<"\nCan't convert negative amount!";
            return;
        }
        cout<<"\nThe equivalent money in Rupees is : "<<46*dollar;
}
int main( )
{
    int amount;
    cout<<"\nEnter the amount in dollars you want to convert: ";
    cin>>amount;
    convert(amount);
    return 0;
}

The output when you type a positive value is:

Enter the amount in dollars you want to convert: 5

The equivalent money in Rupees is : 230

The output when you enter a negative value is:

Enter the amount in dollars you want to convert: -1

Can't convert negative amount!

As can be seen from the output in the second case, once the return statement is encountered the program will stop executing the function (thus it does not calculate the value of 46*dollar if the value of dollar is negative).


void main ( ) and int main ( )

The main( ) function can be written in one of two ways. Either you can use:

void main ( )

or you can use:

int main ( ) returns an integer value while void main ( ) doesn’t return anything. Consider the following program:

Since ‘test’ is equal to 1, the compiler will go into the body of if. It will display "You typed 1" on the screen. Then the compiler will return a value of 1. Generally a return value of a non-zero number is used when errors are encountered. You can't use this return value anywhere else in your program (Why? Because the caller for the main ( ) function is your operating system). In other functions (functions other than ‘main’ ), you can make use of the return value. After returning the value, the program exits. This means that the compiler will not even read the remaining few lines and hence nothing else will display on the screen. The compiler will quit once any integer has been returned by the main ( ) function.

If you type anything other than 1 for test, the compiler will skip the ‘if’ body, display the last statement and then return 0.

Better to use int main ( )?

We could now delve one step further into the topic. Which one is better? Or which one should we use and why? Void is generally used to declare functions that do not return values.

When you use int main ( ), the main function returns an integer to the operating system (since the OS is what calls the program and in turn the main function). Returning a value from main ( ) is like an exit function. The value is returned to the operating system and the program terminates. What will the OS do with your returned value? Actually, the OS never wants to know what you return. The program which started your program might need to know. In any OS, a program when running is called a "process". When booting up, the operating system starts the first process (called "init" in UNIX systems). Thereafter the first process starts other processes such as a shell (shell is just a program, which reads commands from the user and converts it to system calls). So when you write a program and execute it in the shell, the shell starts your program. So now, the shell is the parent process of your program (and your program is the child of the shell). Now, in the same way, suppose you want one of your programs to load another program to do a particular job and you want to know just whether the job was successful or not, then the OS gets the exit code of the child process and gives it to the parent process; just like returning from a function. So it is a standard to give the exit code as '0' for a success and any non-zero integer for an error. When programming in C/C++ you can give this exit code when you return from the main function. So you've to declare main as 'int main( )' to do that. If you declare it as 'void main( )' C++ wont allow you to set a value to be returned to your parent program. So the variable which should contain the return code will be filled by nothing, which means that memory can be in any state (unpredictable). Hence you have no control on what value your parent process gets when your child program exits. This is not just for UNIX, it holds good for MSDOS and Windows too. In the UNIXes the shell is usually 'sh' or 'bash'. In MSDOS the shell is called 'command.com'. In Windows the shell is 'explorer.exe'.

Hence it's always better to use int main ( ) along with a return value at the end of the main ( ) function. A return value of zero indicates a normally terminated program. A non-zero value is used in case of errors. Of course this does not mean that a program written with void main ( ) won’t work; but it is better to avoid writing such programs.

A practical example over here (along with some basics of batch programming).


exit()

There is a function called exit ( ) which can be used to terminate (or break out from) the program. The function is:

void exit (int r);

where ‘r’ is an integer value returned to the OS. Usually a value of 0 is used to indicate normal termination while a non-zero number is used in the case of abnormal termination (due to errors). Thus, the syntax (or function call) will be:

exit (0);

or

exit (1);

Instead of using integers we can also use two predefined macros: EXIT_SUCCESS (which is equivalent to 0) or EXIT_FAILURE (which is a non zero number).

The exit ( ) function is declared in the stdlib.h library file. Hence you should type:

#include <stdlib.h>

in case you want to use this function.


Using ‘return’ to break out from loops

The ‘return’ statement will return program flow control to the caller and this feature can be used to break out from loops. An example program is given below:

The output of the above program will be:

As can be seen above, the return statement has acted like a ‘break’ statement to return control flow to the main ( ) function.


Go back to the Contents Page


Copyright © 2004 Sethu Subramanian All rights reserved.