Tuesday, 25 June 2013

Functions - III

Inline Functions

The main objective of using functions in a program is to save memory space, which becomes appreciable when a function is likely to be called many times. However, every time a function is called it takes a lot of extra time in executing a series of instructions for tasks such as jumping to the function, saving registers, pushing arguments into the stack and return to the calling function. when a function is small, a substantial percentage of execution time maybe spent in such overheads.

One solution to this problem is to use a macro definition, as you would be aware it to be macros from C. Pre-processor macros are used in C. The major drawback with macros is that they are not really functions and hence any error would go unchecked as error checking is not done during compilation. 

C++ has a feature which presents the perfect solution to his problem. To eliminate the cost of calls to small function C++ has a new feature called the Inline Function. An inline function is a function that is expanded in line when it is invoked. That is, the compiler replaces the function call with the corresponding function code (Which you might consider similar to macro expansion). The inline functions are defined as follows :-

inline function-header
{
         function body
}

Example

inline double cube (double a)
{
     return (a*a*a);
}

The above inline function can be invoked by statements like 

c = cube (3.0);

d = cube (2.5+1.5);

On the execution of these statements, the values of c and d will be 27 and 64 respectively. If the arguments are expressions like 2.5+1.5, the function passes the value of the expression , 4 in this case. This makes the inline feature far superior to macros.

It is easy to make a function inline. All we need is to do is to prefix a keyword inline to the function definition. All the functions must be defined before they are called.

*NOTE
We should be extremely careful before making a function inline. The speed benefits of inline functions diminish as the function grows in size. At some point the overhead of the function call becomes small compared to the execution of the function, and the benefits of inline functions will be lost. In such cases, the use of normal functions will be more meaningful. Usually, functions are made inline when they are small enough to be defined in one or two lines.

Limitations

The inline keyword merely sends a request and not a command to the compiler. The compiler may ignore the request if the function definition is too long or too complicated and might compile the function as a normal function.

Some of the limitations where inline functions do not work :-

  • For functions returning values, if a loop, a switch, or a goto statement exists.
  • For functions not returning values, if a return statement exists.
  • If function contains a static variable.
  • If inline functions are recursive.
A program to illustrate the use of inline function

#include<iostream>

using namespace std;

inline float mul (float x, float y)
{
     return (x*y);
}

inline double div (double p, double q)
{
      return (p/q);
}

int main()
{
       float a = 12.965;
       float b = 9.810;

       cout<<mul (a,b)<<"\n";
       cout<<div (a,b)<<"\n";
     
       return 0;
}


The output of the program is 
127.187
1.32161

Default Argument

C++ gives the provision to call a function without specifying all its arguments. In such cases, the function assigns a default value to the parameter which does not have a matching argument in the function call. Default values are specified when the function is declared. The compiler looks at the prototype to see how many arguments a function uses and alerts the program for possible default values. 

Here is an example of a prototype of a function declaration with default values :-

float amount (float principal, int period, float rate =0.15);

The default value is specified in a manner syntactically similar to a variable initialization. The above prototype declared a default value of 0.15 to the argument rate. A subsequent function call like

value = amount (5000, 7);        //Argument for rate is missing

passes the value of 5000 to the principal and 7 to the period and then lets the function use default value of 0.15 for rate.

The call

value = amount (5000, 5, 0.12)  //No argument missing

passes an explicit value of 0.12 to rate.

A default argument is checked for type at the time of declaration and evaluated at the time of call. One important point to note is that only the trailing arguments can have default values and therefore we must add defaults from right to left. We cannot provide a default value to a particular argument in the middle of an argument list. 

Note :- Default arguments are useful in situations where some arguments always have the same value. For instance, bank interest may remain same for all the customers taking a particular type of loan for a particular period. It also provides a greater flexibility to the programmers. A function can be written with more parameters than are required for its most common application. Using default arguments, a programmer can use only those arguments that are meaningful to a particular situation.

Advantages of Default Arguments :-

  • We can use default arguments to add new parameters to the existing functions.
  • Default arguments can be used to combine similar functions into one.

Constant Argument

In C++, an argument to a function can be declared as const  as shown below :-

int strlen ( const char *p);
int length (const string &s);

The qualifier const tells the compiler that the function should not modify the argument. The compiler will generate an error when this condition is violated. This type of declaration is significant only when we pass arguments by reference or pointers.

Function Overloading

As we know overloading means the use of the same thing for different purposes. C++ also permits overloading of functions.This means that we can use the same function name to create functions that perform a variety of different tasks. This is known as function polymorphism in OOP concept.

Using the concept of function overloading we can design a family of functions with one function name but with different argument lists. The function would perform different operations depending on the argument list in the function call. The correct function to be invoked is determined by checking the number and type of the arguments but not on the function type. For example, an overloading add() function handles different types of data as shown below :-

//declarations

int add (int a, int b)                                    //prototype 1
int add (int a, int b, int c)                            //prototype 2
double add (double a, double b)                   //prototype 3
double add (double p, int q)                        //prototype 4
double add (int x, double y)                        //prototype 5

//Function calls

cout<<add (5,10);                       //uses prototype 1
cout<<add (5,10.50,8);                //uses prototype 2
cout<<add (12.5,10.9);                //uses prototype 3
cout<<add (5.78,10);                   //uses prototype 4
cout<<add (5,10.98);                   //uses prototype 5

A function call first matches the prototype having the same number and type of arguments and then calls the appropriate function for execution. A best match must  be unique. The function selection involves the following steps.
  • The compiler firsts tries to find an exact match in which the types of actual arguments are the same and uses that function.
  • If an exact match is not found, the compiler uses the integral promotions to the actual arguments, such as,  
       char to int
       float to double
      to find a match
  • When either of the  fails, the compiler tries to use the built n conversions to the actual arguments and then uses the function whose match is unique. If the conversion is possible to have multiple matches then the compiler will generate an error message. Suppose we use the following two functions 
       long square (long n)
       double square (double x)

       A function call such as square (10)
     
       will cause an error because int argument can be converted to either long        
       or double thereby creating an ambiguous situation as to which version of 
       square() should be used.
  • If all of the steps fail, then the compiler will try the user-defined conversions in the combination with integral promotions and built in conversions to fund a unique match. User defined conversions are often used in handling class objects. 
Note :- Overloading of functions should be done with caution. We should not overload unrelated functions and should reserve function overloading for functions that perform closely related tasks. Sometimes, the default arguments may be used instead of overloading. This may reduce the number of functions to be defined.

Thats all of functions that we need to know as of now.

Tasks :-

Q. Write a C++ program that will illustrate Default argument and function overloading features.

Saturday, 22 June 2013

Functions II


In the previous post I had talked about main functions and function prototyping. In this post I would like to continue on functions and cover all the areas around them.

Call By Reference

Limitations of Call by Value

In C language a function call passes arguments by value. The Called function creates a new set of variables and copies the values of arguments into them. The function does not have access to the actual variables in the calling program and can only work on the copies of the actual values. This mechanism works fine until the function does not need to alter the values of the original variables in the calling program. 

But such demanding situations might arise where we need to change the values of the variables in a calling function. Such as in the case of Bubble sort problem where we need to compare two adjacent elements in the list and interchange their values according the the comparison results if needed. If a function is used for creating a Bubble sort algorithm then it should have the capability to alter the values of variables in the calling functions, which is not possible by call by value method.

Call By Reference

In C++ we use reference variables which enable us to pass parameters to the functions by reference. When we pass an argument by reference, the formal arguments in the called function becomes aliases to the actual arguments in the calling functions. This means that when the function is working with its own arguments it is actually working on the original data. 

An example would make things appear easier, 

void swap ( int &a , int &b )        //a and b are reference variables 
{
         int t = a;
         a=b;
         b=t;
}

Now if m and n are two integer variables, then the function call 

swap (m,n);

will exchange the values of m and n using the aliases a and b.

In C languages this is accomplished by using pointers and indirections.

Return By Reference

A function can also return a reference. Consider the following function :

int & max (int &a, int &b)
{
         if (a>b)
                 
            return a;
         else
           
            return b;
}

Since the return type of max() is int&, the function returns references to a or b. Then a function call such as max (x,y) would yield a reference to either x or y depending on their values. This means that this function call can appear on the left hand side of an assignment statement. That is, the statement

max (x,y) = -1;
is legal and assigns -1 to x if it is larger otherwise -1 is assigned to y.

In the next post I would stress on inline functions, default arguments and function overloading.









Thursday, 20 June 2013

Functions in C++

The Main Function


C language does not specify any return type for the main () function which is the starting point in the execution of the program. The main() definition looks something like this in C -

main()
{

       // main program statements and instructions

}

This is perfectly valid in C as main() is C doesnt return any value.

In contrast C++ has a return value of type int for the main () to the Operating System. The main function in C++ is, therfore defined as follows :-

int main ()
{

 //program statements

return 0;
}

Note :- Since the return type of functions is int by default, the keyword int in the main is optional.

Many Operating systems test the return value to determine if there is any problem. The normal convention is that an exit value of zero means that the program ran successfully, while a nonzero value means there was a problem. The explicit use of a return 0 statement will indicate that the program was successfully executed.

Function Prototyping

Function prototyping is one of the major improvements added to C++ functions from C functions. The prototype describes the function interface to the computer by giving details such as the number and type of arguments and the type of the return value. With function prototyping , a template is always used when declaring and defining a function. When a function is called, the compiler uses the template to ensure that proper arguments are passed, and the return value is treated correctly. These checks and controls didnt exist in the conventional C functions.
 
Function prototype is a declaration statement in the calling program and is of the following form
 
type function-name (argument list );
 
The argument list contains the types and names of arguments that must be passed to the function.
 
Example
 
float volume (int x, float y, float z);
 
Note :- Each argument variable must be declared independantly inside the parentheses i.e. a combined declaration like
 
float volume (int x, float y, z) ; is illegal.
 
In a function declaration, the names of the arguments are dummy variables and therefore they are optional. That is , the form
 
float volume (int , float, float );
 
is acceptable at the place of the abovemetioned declaration. At this stage, the compiler only checks for the type of arguments when the function is called.
 
In the function definition though , names are required because arguments must have a reference inside a function.
 
Example :-
 
float volume ( int a, float b, float c)
{
 
       float v = a*b*c;
       .........................
       .........................
}
 
the function volume () can be invoked in a program as follows :
 
float cube1= volume (b1,w1,h1);   //Calling the function
 
The variables b1, w1, h1 are known as actual parameters which specify the dimensions of cube1. Their types should match with the types declared in the protoype.
 
We can also declare a function with an empty argument list, as in the following example :-
 
void display () ;
 
In C++, this means that the function does not pass any parameters. It is identical to the statement
 
void display ( void);
 
In C an empty parantheses implies any number of argument generally returning garbage values, in C++ though we have a default void type if the parantheses is left empty.
 
Hope to see you again for the next topic.
 
Note :- Each argument variable must be declared independantly inside the parantheses.  

Monday, 10 June 2013

Data Types

Basic Data Types

Both C and C++ compilers support all the built in basic data types. With the exception of void, the basic data types may have several modifiers preceding them to serve the needs of various situations. The modifiers signed, unsigned long and short may be applied to character and integer basic data type.
However the modifier long may also be applied to double. 

Here is a list of all the combinations of basic data types with their size and range for a 16 bit machine.


User Defined Data Types

If you have used C you all must have used user defined datatypes such as struct and union in C. While these data types are legal in C++, some more features have been added to make them suitable for object oriented programming. C++ also permits us to define another user defined data type known as class which can be used just like any other basic data type, to declare variables. The class variables are known as objects, which are of central importance in OOP.

Enumerated Data Type

An enumerated data type is another user defined data type which provides a way for attaching names to numbers, thereby increasing the comprehensibility of the code. The enum keyword automatically enumerates a list of words by assigning them values 0,1,2 and so on. This facility provides an alternative means for creating symbolic constants. The syntax of an enum statement is similar to that of the struct statement.

Derived Data Type

  • Arrays :- The application of arrays in C++ is similar to that in C. And they only exception is that the size of the array should be one larger than the number of characters in the string.
  • Functions :- Functions are a lot different in C++ as compared to C. While some of these changes are simple while others require a new of thinking when organising our programs. Many of these modifications and improvements were driven by the requirements of the Object oriented concepts of C++ . We will discuss them in details later.
  • Pointers :- Pointers are declared and initialised as in C. Examples :- int *ip; ip= &x; *ip=10. C++ adds the concept of constant pointer and pointer to a constant. 
          char * const ptr1 = "GOOD";           //constant pointer
         we  cannot modify the address that ptr1 is initialized to 
         int  const * ptr2 = &m;  //pointer to a constant.

Symbolic Constants

There are two ways of creating symbolic constants in C++
  • Using the qualifier const, and
  • Defining a set of integer constants using enum keyword.
In C++ as in C , any value declared as const cannot be modified by the program in anyway. However there are some differences in implementation. In C++ , we can use const in a constant expression such as :

const int size = 10;
char name [size];
this would be illegal in C. 

Declaration of Variables

We know that in C all variables must be declared before they are used in executable statements. This is true in case of C++ as well. However there is a significant difference between C and C++ with regard to the place of their declaration in the program. C requires all the variables to be defined at the beginning of a scope. When we read a C program, we usually come across a group of variable declaration at the beginning of each scope level. Their actual use appears elsewhere in the scope, sometimes far away from the place of declaration. Before using a variable, we should go back to the beginning of the program to see whether it has been declared and if so, of what type.

C++ allows the declaration of a variable anywhere in the scope. This means that a variable can be declared right at the place of its first use. This makes the program much easier to write and reduces the errors that maybe caused because the variable are declared in the context of their use. The only disadvantage of this style of declaration is that we cannot see all the variables used in the program at a glance.

Thats all for today friends get back to you tomorrow with lots more :)