Posted in C++

C++ function void

This is about empty function in C++.

Starting with nothing the empty functions can do a lot. They actually can help in thousand of other things. How do they function, I will explain in a very laymen manner :

A void function is declared as follows :

void MyFunctionName  (Some parameters if needed)
{  some code.  }

A simple empty function would be :

void hello()
{ 
       cout<<"Hello world"; 
}

This Function when called would print the hello world statement. Most of you would think it worthless. Now consider another one :

void print(char a[]) //print an array
{
   int i=0;
   for (i=0 ; a[i]!='' ; i++)
   {
     cout<<a[i]<<" ";
   }
}

This function will print an array (provided that it has already some data).

Another one :

void save(char n[],int length) //save elements in an array
{
   for(int i=0;a[i]!=' ';i++)
   {
     scanf("%c ",ch);  //for using this you need to include cstdio header...
     if(ch=='\n'){return;}
     a[i]=ch;
   }
}

This time it will save elements into and array until a newline character is not encountered.

Now combining these functions we end up with a simple function which can be understood very easily.

int main() //main program...
{
   char a[30];
   save(a,30);
   print(a);
   return 0;
}

Now this is what the void function did for us right now. We could have used loops to make the same thing but a void function makes it look clean. Apart from this , if someone told you to take in 50 arrays, had you put up several loops inside one another a single loop would do your job and also make a lot times easily understandable.

Void function’s utility doesn’t end here.

I just explained a typical example. They can used in a variety of places ( to print the full value of 100!  🙂  )

Advertisements

One thought on “C++ function void

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s