Showing posts with label Functions. Show all posts
Showing posts with label Functions. Show all posts

Forwarding functions

Sometimes it is required to seperate the interface from implementation and 'forwarding functions' can be useful. The interface class can forward the work to the implementation keeping the interface clean and minimal.

The following is a simple example where function f() forwards its work to function g():



//g.h
#pragma once

bool
g(int x)
{

if
(x%2 == 0)
return
true;
else
return
false;
}



//f.h
#pragma once

bool
f(int x);


//f.cpp
#include<iostream>

#include "f.h"
#include "g.h"

bool
f(int x)
{

return
g(x);
}



//main.cpp
//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
#include<iostream>

#include "f.h"

using namespace
std;

int
main()
{

if
(f(20))
cout<<"TRUE"<<endl;
else

cout<<"FALSE"<<endl;

return
0;
}





There are couple of things to keep in mind when writing them. See here.

You can read more about seperating Interface and Implementation here.

Using constants with functions

There always seems to be confusion in using const with functions. I am not referring to const functions that have const after the function name, that is straightforward. Also, the way functions behave when you have const before them is different than the built-in types. I have earlier provided a table for that.

Here is a simple program that shows different types of const with functions.



//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
#include<iostream>
#include<string>

using namespace
std;

class
A
{

public
:
int
x;
};


class
B
{

public
:
string y;
};


A* const createA()
{

return
(new A);
}


const
B* createB()
{

return
(new B);
}


int
main()
{

A* a = NULL;
a = createA();
a->x = 100;
cout<<"a.x = "<<a->x<<endl;
delete
a;

const
B* b = NULL;
b = createB();
//b->y = "Hello"; - Compilation error because b is constant
(const_cast<B*>(b))->y = "Hello";
cout<<"b.y = "<<b->y<<endl;
delete
b;

A* const a2 = NULL;
//a2 = createA(); - Compilation Error:
// you cannot assign to a variable that is const

A* const a3 = new A; //not possible to change what a3 points to now
a3->x = 23456;
cout<<"a3.x = "<<a3->x<<endl;
delete
a3;

return
0;
}






The output is as follows:

Passing Variable arguments in functions

Sometimes it becomes necessary to have variable number of arguments in the function. One way is to overload the function but that may be unnecessary for simple logic. We can use access variable-argument lists macros in the functions. Here is a simple example:





//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//Program to show how to use variable number of arguments

#include<iostream>
#include <stdarg.h> //needed for va_ macros
using namespace std;

//List Should be terminated by -1 in our case
int Add(int a,...)
{

int
total = a;
int
l_ParamVal=0;

//Declare a va_list macro and initialize it with va_start
va_list l_Arg;
va_start(l_Arg,a);

while
((l_ParamVal = va_arg(l_Arg,int)) != -1)
{

total+= l_ParamVal;
}


va_end(l_Arg);
return
total;
}


int
main()
{

cout<<"Result of Add(2) = "<<Add(2, -1)<<endl;
cout<<"Result of Add(2, 3) = "<<Add(2, 3, -1)<<endl;
cout<<"Result of Add(2, 3, 31) = "<<Add(2, 3, 31, -1)<<endl;
cout<<"Result of Add(2, 3, 31, 77) = "<<Add(2, 3, 31, 77, -1)<<endl;

cout<<endl;
return
0;
}

These type of functions that take variable number of arguments are also referred to as 'Variadic Functions'. See more details here.

The output is as follows:

Passing unnamed arguments in functions

It is possible to pass an unnamed argument in C++ function. The unnamed argument indicates that argument is unused. Typically unnamed arguments arise from the simplification of code or from planning ahead for extensions. In either case, leaving the argument in place, although unused, ensures that the callers are not affected by the change. Simple example as follows:



//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//Simple example of unnamed arguments
#include<iostream>

using namespace
std;

void
someFunc(int a, int)
{

cout<<"Only a is defined to "<<a<<endl;
cout<<"The second argument is dummy"<<endl;
}


int
main()
{

someFunc(15, 100); //100 is dummy

cout<<endl;
return
0;
}






The output is as follows:

Advanced features of C++ functions

There are 3 advanced features of C++ functions as compared to C. They are Call by Reference, Function Overloading and Default Arguments. You can read more about them here.

A simple program showing all the three features as follows:



//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//Example of pointer to const and const pointer
#include<iostream>

using namespace
std;

//Call by reference
void swap(int& a, int &b)
{

int
temp = a;
a = b;
b = temp;
}


//Overloaded function: Call by reference (pointers)
void swap(int *a, int *b)
{

int
temp = *a;
*
a = *b;
*
b = temp;
}


//Pass by value with Default arguments
void doSwap(int a, int b = 1)
{

swap(a,b);
cout<<"After Local Swap: a = "<< a <<" b = "<< b <<endl;
}


int
main()
{

int
a = 10, b = 17;
cout<<"Before Swap : a = "<< a <<" b = "<< b <<endl;
swap(a, b);
cout<<"After Swap 1: a = "<< a <<" b = "<< b <<endl;
swap(&a, &b);
cout<<"After Swap 2: a = "<< a <<" b = "<< b <<endl;
doSwap(a, b);
doSwap(a);
cout<<"After DoSwap: a = "<< a <<" b = "<< b <<endl;

return
0;
}






The output is as follows:


Difference between procedures and functions in C++

In very simple terms in C++ a procedure is a function with return type as void.

Generally speaking we use the term procedure to refer to a routine, like the ones above, that simply carries out some task (in C++ its definition begins with void). A function is like a procedure but it returns a value; its definition begins with a type name, e.g. int or double indicating the type of value it returns. Procedure calls are statements that get executed, whereas function calls are expressions that get evaluated.

A simple program to show the difference as follows:


//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//This program shows difference between functions and procedures
#include<iostream>

using namespace
std;

//function
bool checkIfPositive(int x)
{

if
(x >= 0)
return
true;
return
false;
}


//procedure
void printIfPositive(int x)
{

bool
isPositive = checkIfPositive(x);
if
(isPositive)
cout<<"x is positive and its value is "<<x<<endl;
}


int
main()
{

printIfPositive(3);
printIfPositive(-54);
printIfPositive(710);
return
0;
}


The output is as follows:


How Do I Color-Highlight PHP Source Codes

If you’ve been a regular reader of this blog you might have wondered
how I highlight PHP code using different colors. Your prompt answer would be,
using some software. Well not exactly as PHP has built-in feature for highlighting
source code. And of course I use that.


Here are some of the different methods that you can use to highlight PHP source
code, you may use any one of them depending upon what your intended purpose
is.


1. If have set-up PHP as explained in Configuring
Apache Web Server and PHP
then you can just name your PHP files like
“filename.phps” to tell PHP to highlight and show the file upon
request and not execute it. You can use this method when you want to link the
highlighted source from some web page. You cannot, however, embed source code
into web pages using this method.


PHP Source Code Highlighting - Using .phps Files


2. You can use the following function to highlight any
PHP (.php) script file:


highlight_file('filename.php');


You just have to pass the filename to this function and PHP will highlight
and output the code to the browser.


Main benefit with this is you can embed source code into your web pages wherever
you want.


e.g.:


<?php



echo "<h1>Blah Blah Blog</h1>";


echo 
"<h2>Highlighting PHP Source Code</h2>";




echo 
"<p>blah blah blah!!</p>";


echo 
"<p>Write anything you want and embed source code (highlighted)</p>";


echo 
"<p>Embedded source code is listed below:</p>";




highlight_file('highlight_file.php');




?>


PHP Source Code Highlighting  - Using highlight_file() Function


3. There are times when you just want to highlight a
single line of code which can be done using:


highlight_file('string
here')
;


It could be used when you have lost of unrelated lines of code to highlight.
In other words, when the codes are not together but are sprinkled throughout
the page. For this you don’t have to create any files to be highlighted,
just use this function with thee source code string.


e.g.:



<?php



echo "<h1>Blah Blah Blog</h1>";

echo 
"<h2>Highlighting PHP Source Code</h2>";



echo 
"<p>First String: <br />";

highlight_string("<?php echo \"<h1>Blah Blah Blog</h1>\"; ?>");



echo 
"<br />Second String: <br />";

highlight_string("<?php foreach($keywords as $keyword) ?>");



echo 
"</p><p>blah blah blah blah <br />blah blah blah</p>";

echo 
"<p>Third highlighted String: <br />";

highlight_string("<?php if(isset($s)) ?>");



echo 
"<p>Notice how many unrelated code strings are here. The best way to format them in this condition is to use ";

highlight_string("<?php highlight_string(\"string\"); ?>");

echo 
"function </p>";



?>


Which would show up like below:


PHP Source Code Highlighting  - Using highlight_string() Function


One interesting thing that you can play with, regarding syntax highlighting
is the “php.ini” file. Look for these lines in that file:


; Colors for Syntax Highlighting mode. Anything that's acceptable in

; <span style="color: ???????"> would work.

highlight.string = #DD0000

highlight.comment = #FF9900

highlight.keyword = #007700

highlight.bg = #FFFFFF

highlight.default = #0000BB

highlight.html = #000000


Here, as you can see, the colors for highlighting different parts of the code
are defined. You can change these to alter the colors that are use for highlighting.
Colors are in HEX RGB format (same as HTML color code).


NOTE: If you don’t seem to be able to see the source
code highlighted you might need remove the ";" (semi-colons) from
the starting of each of the "highlight." line so it looks like the
above code:


; Colors for Syntax Highlighting mode. Anything that's acceptable in

; <span style="color: ???????"> would work.

;highlight.string = #DD0000

;highlight.comment = #FF9900

;highlight.keyword = #007700

;highlight.bg = #FFFFFF

;highlight.default = #0000BB

;highlight.html = #000000


If only “.phps” PHP source files are not getting highlighted, you’ll
need to set-up PHP as described in Configuring
Apache Web Server and PHP
.


Previous Posts:


All About User-Defined Functions in PHP

User-Defined Functions in PHP


So far we’ve been using PHPs built-in functions to do our tasks; we also
declared and used user-defined function in the post Creating
a Simple Visitor Counter in PHP
. However, we didn’t discuss much
about them. For those of you who are curious to know more about user-defined
functions or those who’d doubts, I’ve written this post. Read along
to know more about user-defined functions.


Declaring functions


In PHP functions are declared using the keyword ‘function’ as below:


function func-name(arg-list)


{

    
…

}


Here ‘arg-list’ may be empty if you don’t want the function
to take any arguments.


If you remember from the post Creating
a Simple Visitor Counter in PHP
, we’d stated that no matter whether
the function returns a value or not, no return type has to be specified for
the function (unlike C/C++).


a. Functions having parameters


function myfunc($a)


{

    echo 
$a;


}


b. Functions returning values


function myfunc($a)


{

    return 
2*$a;


}


Scope of variables inside and outside of function




  1. Variables declared inside a function are called local variables and re
    only accessible within the function.




  2. Variables declared outside functions are called global variables STILL
    they are NOT directly accessible from inside functions.




Have a look at the following code:




function 
myfunc()


{

    
$a=10;


}

echo 
$a;


//$a will not be accessible




//for global varaible

$a=10


function myfunc2()


{

    
//again $a not accessible


    
echo $a;


}



There is nothing we can do to make local variables accessible outside the
function however global variables can be made accessible inside functions by
explicitly defining that particular function as ‘global’ inside
the function.


$a=10


function myfunc2()


{

    global 
$a;


    
//now $a=10 is accessible


    
echo $a;


}



Naming functions




  1. Two functions cannot have the same name neither your functions can have
    the same name as an existing function. PHP DOES NOT SUPPORT FUNCTION OVERLOADING.




  2. Function name may have letters, digits and underscores.




  3. Function name cannot begin with a digit.




  4. Functions can be of the same name as a variable though.




Previous Articles:


Inline Functions and their Uses

It’s a good practice to divide the program into several functions such
that parts of the program don’t get repeated a lot and to make the code
easily understandable.


We all know that calling and returning from a function generates some overhead.
The overhead is sometimes to such an extent that it makes significant effect
on the overall speed of certain complex and function-oriented programs. In most
cases, we have only a few functions that have extensive use and make significant
impact on the performance of the whole program.


Not using functions is not an option, using function-like macros is an option,
but there is a better solution, to use Inline Functions.


Yes, like it sounds, inline functions are expanded at the place of calling
rather than being “really called” thus reducing the overhead. It
means wherever we call an inline function, compiler will expand the code there
and no actual calling will be done.


Member functions of classes are generally made inline as in many cases these
functions are short but any other function can be inline too. Functions are
made inline by preceding its definition with the keyword “inline”
as shown in the example below:



// precede the definition
// of function with "inline"
// it's optional to do so for
// the prototype
inline ret-type func-name(arg-list...)
{
...
...
...
}


Member functions (class) can be made inline as below:



class myclass
{
private:
...
...

public:
ret-type func-name(arg-list...);
...
...
};

inline ret-type myclass::func-name(arg-list...)
{
...
...
}



Or simply as



class myclass
{
private:
...
...

public:
inline ret-type myclass::func-name(arg-list...)
{
...
...
}
...
...
};


Short member functions are usually made inline as above.


Please mote one thing though, inline is a request to the compiler and not a
command which means it depends on the compiler and the conditions whether a
particular function will be really made “inline” or not.


As inlining increases duplication of parts of code, performance will be gained
at the expense of program size, which is pretty obvious. As I’ve said
not all functions make major impact on the overall performance of the program.
So we should carefully select which functions to inline and which not to, because
if we inline many functions we can’t be sure of whether it’d do
any better to the performance, but it’s for sure that program size will
increase unnecessarily.


Related Articles:


What is 'this' Pointer?

Have a look at the following code:



// program to illustrate 'this'
// pointer
#include <iostream.h>

// class
class myclass
{
int a;

public:
myclass(int);
void show();
};

myclass::myclass(int x)
{
// same as writing a=10
this->a=x;
};

void myclass::show()
{
// same as writing cout<<a;
cout<<this->a;
}

// main
void main()
{
myclass ob(10);

ob.show();
}


Now look at the awkward looking lines:


this->a=x;

and

cout<<this->a;

As you can see ‘this’ looks like a pointer to an object which is
neither declared neither as a local nor as a global variable. So how the member
function is using it?


Actually ‘this’ is a special argument which is passed implicitly
to every member function. It points to the specific object of the class that
generated the call to that function.


So if we have the following line of code:


  myclass ob1, ob2;
ob2.show();

then the func function will be passed a ‘this’ pointer pointing
to the object that invoked it (i.e. ob2)


Actually there is no use of ‘this’ pointer like this as every member
referenced inside a member function will automatically be relative to the object
that generated the call to the function.


So


  myclass::myclass(int x)
{
this->a=x;
};

And


  myclass::myclass(int x) 
{
a=x;
};


Codes are equal and do the same thing.


This is not to say that ‘this’ pointer has no practical use as
it is frequently needed when overloading operators.


NOTE: Please keep in mind that static member functions are not passed the ‘this’
pointer.


Related Articles:


Friend Functions of Class

First, have a look at the following code:



// Using Friend Functions
#include <iostream.h>

class myclass
{
int a;

public:
friend int geta(myclass);
void seta(int x){a=x;}
};

// notice how the friend function
// can access even the private members
// of the class
int geta(myclass ob)
{
return ob.a;
}

void main()
{
myclass obj;

obj.seta(100);

// accessed as usual
cout<<geta(obj);
}



Did you notice the specialty?


In the above example program the function geta() is just a general function
(friend of class, of course) but still it is able to access the private member
of the class (i.e. the variable ‘a’). The function is also called
as usual since it is not a member function.


This is because by declaring any non-member function as friend inside a class,
gives it access to the entire Private and Protected members of that class.


Many of you would be wondering what is gained by doing this all?


The answer is that there are circumstances when its use simplifies certain
operations, it is also widely used in overloading operators besides this there
are some other uses of friend functions none of which can be discussed here,
so we leave the use friend functions for future articles!


Related Articles:


Static Member Functions of Class

Much like the Static
Members
, there also exist static member functions. Just as static members,
static functions can also be accessed independently of any specific object and
thus its primary use is to pre-initialize static members before creation of
any object.


The following program illustrates how static member functions are declared
and used:



// Static Member Functions
#include <iostream.h>

class myclass
{
// declare a
static int a;

public:
// static function
static void init(int x){a=x;}

int get(){return a;}
};

// define a
int myclass::a;

void main()
{
// static functions may
// be called independently
// using the class name
myclass::init(100);

myclass obj;

cout<<obj.get();
}


In the above example the static members function (init() ) is used to initialize
the static member variable ‘a’ before object creation.


A few points to remember:




  • Static member functions can only access other static member of the class
    or global data.




  • Static member functions can’t have a non-static overloaded version.




  • They don’t have a ‘this’ pointer, this is because static
    functions can be called irrespective of specific object (using the class
    name and the scope resolution operator ‘::’).




With these restrictions they have very limited applications, one of them as
we discussed is to initialize other static members before object creation.


Related Articles:


Parameterized Constructors of Derived Classes

In the previous article Constructors
and Destructors of Derived Classes
, we’re discussing about the
calling conventions of Constructors and Destructor functions of derived classes
whose base class also had them. There was one thing special about those constructors;
none of them were taking arguments.


If only the derived’s constructor takes parameters then also its O. K.
but what if both the base and derived class contains parameterized constructors
(as is obvious from the code below).



// this code contains ERRORS

// base class
class base
{
int a;

public:
base(int n)
{
//...
}
};

// derived class
class derived:public base
{
int b;

public:
derived(int m)
{
//...
}
};

//main
void main()
{
base b(10); //ok

derived d(10); // ERROR!!
// base's constructor
// will also be called and
// it needs parameters too !!
}



How’d you pass arguments to the base class constructor?


To answer this, we need to introduce Expanded from of Constructor Declaration
(of the derived class).



derived-constructor (arg): base1 (arg),
base2 (arg),
...
baseN (arg)
{
...
...
}


Here base1, base2 etc. are constructor functions of base classes, which the
derived class inherits.


Let’s have a look at an example program to understand this declaration:



// this code is ok

// base class
class base
{
int a;

public:
base(int n){a=n;}
};

// derived class
class derived:public base
{
int b;

public:
// since this class is derived
// from only one class 'base'
// therefore only one constructor
// is listed
derived(int m1,int m2):base(m2)
{b=m1;}
};

// main
void main()
{
base b(10); //ok

derived d(10,100); //ok
}




One thing to note here is, the argument which is to be passed to the base’s
constructor should be declared and accepted from the derived class constructor,
as in the line


derived(int m1,int m2):base(m2)
{b=m1;}


Here derived’s constructor is only using the parameter m1 but is accepting
another parameter m2 which is to be passed along to the constructor of the base
class.


Let us have a look at another example program which will clear all the confusions.
Keep reading the comments!



#include<iostream.h>

// base class (1)
class base1
{
protected:
int a;

public:
base1(int p1){a=p1;}
};

//base class (2)

class base2
{
protected:
int b;

public:
base2(int p2){b=p2;}
};

// derived class (1)

class derived1:public base1
{
protected:
int c;

public:
derived1(int p3,int p4):base1(p4)
{c=p3;}

void show(){cout<<a<<"\n"<<c;}
};

//derived class (2)

class derived2:public base1, public base2
{
public:
// this class inherits two base classes

// therefore we are using two base
// class constructors in the declaration
derived2(int p5,int p6):base1(p5),
base2(p6)
{
// empty


// used only to call the base's
// constructors with the passed
// arguments

// derived class constructor may not
// use any arguments passed to it
}

void show(){cout<<a<<"\n"<<b;;}
};

// main

void main()
{
derived1 d1(10,20);
derived2 d2(100,200);

d1.show();
cout<<endl;
d2.show();
}



Related Articles:


Constructors and Destructors of Derived Classes

Classes can have Constructors and/or Destructors and Derived Classes are no
different.


Situation remains understandable until both the base and its derived class
have Constructors and/or Destructors. Since the derived class contains more
than one Constructors and/or Destructors, it becomes confusing which one will
be called when.


This is because when an object the inherited class is constructed both the
constructors (base’s and its own) should be invoked and same applies when
it gets destructed.


This article will clear all this!


Consider the following example program:



// -- INHERITANCE --
// Constructors, Destructors
// and Inheritance
#include<iostream.h>

// base class
class base
{
public:
base(){cout<<"Constructing Base\n";}
~base(){cout<<"Destructing Base\n";}
};

// derived class
class derived:public base
{
public:
derived(){cout<<"Constructing Derived\n";}
~derived(){cout<<"Destructing Derived\n";}
};

void main(void)
{
derived obj;

// do nothing else, only
// construct and destruct
// the inherited class object
}

OUTPUT:


  Constructing Base
Constructing Derived
Destructing Derived
Destructing Base
Press any key to continue


So here is the general rule:



Constructors are called in the order of derivation and Destructors in
the reverse order.



One more example will clear the confusions, if any.:



// -- INHERITANCE --
// Constructors, Destructors
// and Inheritance
#include<iostream.h>

// base class (1)
class base
{
public:
base(){cout<<"Constructing Base\n";}
~base(){cout<<"Destructing Base\n";}
};

// derived class
// derived form 'base'
class derived1:public base
{
public:
derived1(){cout<<"Constructing Derived1\n";}
~derived1(){cout<<"Destructing Derived1\n";}
};

// derived from a derived class
// 'derived1'
class derived2:public derived1
{
public:
derived2(){cout<<"Constructing Derived2\n";}
~derived2(){cout<<"Destructing Derived2\n";}
};

void main(void)
{
derived2 obj;

// do nothing else, only
// construct and destruct
// the inherited class object
}

OUTPUT:


  Constructing Base
Constructing Derived1
Constructing Derived2
Destructing Derived2
Destructing Derived1
Destructing Base
Press any key to continue

Related Articles:


How String Functions Work? Part II

This is the second part of the article How
String Functions (strinh.h) Work?


Here we'll be designing our own version of some other commonly used standard
library string manipulation function that we discussed in the article String
Manipulation Functions (string.h) II.


These will help increase your programming skills further.


mystrlwr():



// mystrlwr function
#include<iostream.h>

// -- FUNCTION PROTOTYPES --
char *mystrlwr(char *);
// -- ENDS --

void main()
{
char ch[]="C++ ProGramming123";

cout<<mystrlwr(ch);
}

char *mystrlwr(char *str)
{
char *temp;
temp=str;

while(*str!='\0')
{
// change only if its a
// UPPER case character
// intelligent enough not to
// temper with special
// symbols and numbers
if(*str>=65 && *str<=90)
*str+=32;
str++;
}
return temp;;
}


mystrupr():



// mystrupr function
#include<iostream.h>

// -- FUNCTION PROTOTYPES --
char *mystrupr(char *);
// -- ENDS --

void main()
{
char ch[]="C++ ProGramming123";

cout<<mystrupr(ch);
}

char *mystrupr(char *str)
{
char *temp;
temp=str;

while(*str!='\0')
{
// change only if its a
// UPPER case character
// intelligent enough not to
// temper with special
// symbols and numbers
if(*str>=97 && *str<=122)
*str-=32;

str++;
}
return temp;
}

mystrncat():



// mystrncat- function
#include<iostream.h>

void mystrncat(char *,const char *,int);

void main(void)
{
char ch[]="This is great!";
char ch2[25]="Yes ";
mystrncat(ch2,ch,6);

cout<<ch;
cout<<endl;
cout<<ch2;
}

void mystrncat(char *str1,const char *str2,int n)
{
int i=0;
int len=0;

// skip to the end of the first
// string(target)
while(str1[len]!='\0')
len++;

// start copying 'n' characters
// from the start of the
// second string (source)
// to the end of the
// first (target)
while(i<n)
{
str1[len]=str2[i];
i++;len++;
}
str1[len]='\0';
}

mystrncpy():



// mystrncpy- function
#include<iostream.h>

void mystrncpy(char *,const char *,int);

void main(void)
{
char ch[]="This is great!";
char ch2[20];

mystrncpy(ch2,ch,6);

cout<<ch;
cout<<endl;
cout<<ch2;
}

void mystrncpy(char *str1,const char *str2,int n)
{
int i=0;

// copy 'n' characters
// from str2 to str1
while(i<n)
{
str1[i]=str2[i];
i++;
}
// put the end of
// string identifier
str1[i]='\0';
}

mystrrev():



// mysrtrev function

#include<iostream.h>

char *mystrrev(char *);

void main(void)
{
char ch[]="Programming";
cout<<mystrrev(ch);

cout<<ch;
}

char *mystrrev(char *str)
{
char temp;
int len=0;
int i,j;

// find the length
while(str[len]!='\0')
len++;

j=len-1;

for(i=0;i<len/2;i++)
{
// interchange the
// characters from
// the beginning to
// the end
temp=str[j];
str[j]=str[i];
str[i]=temp;
j--;
}

return str;
}

Related Articles:


What is Polymorphism?

Polymorphism means to have one interface for different methods or functions.
It is the ability through which we can do different operations (by calling different
functions) from the same interface.


In C++ functions and operators can be made to be polymorphic, but in this article
we’ll only be discussing about polymorphic functions.


There can be two types of polymorphism which are discussed below:


Compile-Time Polymorphism: When we have two or more polymorphic function (overloaded
functions) and the call to a particular function is resolved (or known) at the
compile-time, it is called compile-time polymorphism.


The following example program illustrates this. Please read the comments for
further information.


   // program to demonstrate
// compile-time polymorphism
#include<iostream.h>

// -- FUNCTION PROTOTYPES --
// -- OVERLOADED FUNCTIONS --
void func(int);
void func(char *);
// -- ENDS --


void main()
{
// by seeing the argument

// passed, anyone can tell
// which version of the
// function is being called
// hence call to particular
// polymorphic functions is
// resolved or known at the
// time of compilation
func(10);
func("Polymorphism");
}

void func(int a)
{
cout<<a;
cout<<endl;
}

void func(char *str)
{
cout<<str;
cout<<endl;
}


Run-Time Polymorphism: When the call to a particular function (out of the many
polymorphic functions) is not resolved (or known) until execution then it is
called run-time polymorphism.


The following example program illustrates this. Pay extra attention to the
comments!



// Program to demonstrate
// run-time polymorphism
#include<iostream.h>

// -- FUNCTION PROTOTYPES --
void func1();
void func2();
// -- ENDS --

void main()
{
int ch=0;
// here pointer to function
// is declared which will
// be used to call one of
// the two functions
void (*ptr)();

while(ch!=3)
{
cout<<"1> Call Func1";
cout<<"\n2> Call Func2";
cout<<"\n3> Quit\n";

cin>>ch;

switch(ch)
{
case 1:
// make 'ptr' point
// to func1
ptr=func1;
break;

case 2:
// make 'ptr' point
// to func2
ptr=func2;
break;
}

// call whichever
// function is selected
// PLEASE NOTE THAT IT IS
// NOT POSSIBLE TO TELL
// WHICH OF THE TWO
// FUNCTION WILL BE
// CALLED. HENCE CALL
// TO A PARTICULAR
// PLOYMORPHIC FUNCTION
// REMAINS UNRESOLVED
(*ptr)();
}
}

// -- FUNCTIONS DEFINITION --
void func1()
{
cout<<"Called Func1!\n";
}

void func2()
{
cout<<"Called Func2!\n";
}
// -- ENDS --



Good-Bye!


Related Articles:


Array of Functions

In the article
Pointers to Function
, we saw how pointers can be made to point
at functions and hence can be used to invoke them.


By far the most important use of pointers to functions is to have arrays of
functions. This can be achieved as stated below


You already know that we can have arrays of pointers and pointers can be made
to point at functions. So combining both we can have array of pointers to functions
put differently, we can have array of functions.


The example program below demonstrates how we can have array of functions;
please note that this concept is mostly used in writing compilers and interpreters,
so you shouldn’t expect the program to do anything serious or useful!


  // Program to demonstrate
// array of functions
#include<iostream.h>

// -- FUNCTION PROTOTYPES --
void func1();
void func2();
void func3();
void func4();
void func5();
// -- ENDS --

void main()
{
// notice the prototype
void (*ptr[5])();

// arrays are made to point
// at the respective functions
ptr[0]=func1;
ptr[1]=func2;
ptr[2]=func3;
ptr[3]=func4;
ptr[4]=func5;

// now the array elements
// point to different functions
// which are called just like
// we access the elements of
// an array
for(int i=0;i<5;i++)
(*ptr[i])();
}

// -- FUNCTIONS DEFINITION --
void func1()
{
cout<<"Called Func1!\n";
}

void func2()
{
cout<<"Called Func2!\n";
}

void func3()
{
cout<<"Called Func3!\n";
}

void func4()
{
cout<<"Called Func4!\n";
}

void func5()
{
cout<<"Called Func5!\n";
}
// -- ENDS --

Good-Bye!


Related Articles:


String Manipulation Functions (string.h) II

This is the continuation of the article String
Manipulation Functions (string.h)
in which we’re discussing about
the string manipulation functions.


Here I have listed 8 functions along with their prototype (simplified) and
a short description.


One thing to note here is that unlike the last article on this topic, I have
not included example programs, since the functions (with their prototypes) are
pretty much straightforward.



strlwr:


Prototype: char *strlwr(char *)

This function converts the given string to lowercase and returns the same.


strupr:


Prototype: char *strupr(char *)

This function converts the given string to UPPERCASE and returns it.


strncat:


Prototype: strncat(char *str1, const char *str2, int n)

It appends first ‘n’ characters of str2 to the end of str1.


strncpy:


Prototype: int strncmp(char *str1, const char *str2, int n)

This function compares first ‘n’ characters of str1 with str2,
it returns 0 if compare was successful.


stricmp:


Prototype: int stricmp(const char *str1, const char *str2)

It compares two strings str1 and str2 without regard to case and returns
0 on being successful.


strnicmp:


Prototype: int strnicmp(const char *str1, const char *str2, int n)

This function compares first ‘n’ characters of str1 with str2
without regard to case.


strrev:


Prototype: char *strrev(char *)

This function reverses the given string and returns it.


stcstr:


Prototype: char *strstr(const char *str1, const char *str2)

This function returns the pointer to where the first occurrence of string
str2 is found inside str1.


Good-Bye!


Related Articles:


String Manipulation Functions (string.h)

This article discusses about the classic string manipulation functions defined
in the string.h header file.


From quite a while peoples have been asking me to write an article on the standard
library string manipulation functions. These functions are defined in the string.h
header file, so you must include it to use them.


There are dozens of string functions in the string.h header
file and thus it is difficult to list them all. So rather than listing them
all I would be discussing in detail about only few commonly used string manipulation
functions along with an example program illustrating how each function is used.


strlen:


  Prototype: int strlen(const char *string);

This function takes the base address of the string as the argument and returns
the number of characters in it (including spaces).


  // strlen() string manipulation
// function
#include<iostream.h>
#include<string.h>

void main(void)
{
char ch[]="String Manipulation";

cout<<strlen(ch);
}

OUTPUT:

   19

strcpy:


  Prototype: strcpy(char *target, const char *source);

This function takes two arguments (base address of two strings) and copies
the contents of the source string to the target string.


It doesn't check bounds thus its our responsibility to be sure that target
string is enough to store the contents of the source string.


  // strcpy - string manipulation
// function
#include<iostream.h>
#include<string.h>

void main(void)
{
char source[]="C++";
char target[10];

strcpy(target,source);

cout<<source;
cout<<endl;
cout<<target;
}

OUTPUT:

   C++
C++

strcat:


  Prototype: strcat(char *target, const char *source);

It concatenates or appends the source string at the end of the target string.


Target string is itself concentrated so it must be big enough to hold the concatenated
characters.


  // strcat - string manipulation
// function
#include<iostream.h>
#include<string.h>

void main(void)
{
char source[]="C++";
char target[20]="I like ";

strcat(target,source);

cout<<source;
cout<<endl;
cout<<target;
}

OUTPUT:

   C++
I like C++

strcmp:


  Prototype: int strcmp(const char *string1, const char *string2);

This function compares two strings and returns 0 if they are identical or else
returns a non-zero value.


Case (lower or upper) does matters, thus c++ and C++ are not the same according
to this function.


  // strcmp - string manipulation
// function
#include<iostream.h>
#include<string.h>

void main(void)
{
cout<<strcmp("c++","C++");
cout<<endl;

cout<<strcmp("Jerry","Jerry");
}

OUTPUT:

   1
0

Good-Bye!


Related Articles:


Check out this stream