Headlines News :
Home » , , » Function in c++ full tutorial about function

Function in c++ full tutorial about function

Written By Durgesh on Thursday 1 March 2012 | 00:50

privious tutorial we know about c++ and variable in c++ in we know what is function and how we use  function in c++
In general, functions are blocks of code that perform a number of pre-defined commands to accomplish something productive
The most important functional (Pun semi-intended) question is why do we need a function? Functions have many uses. For example, a programmer may have a block of code that he has repeated forty times throughout the program. A function to execute that code would save a great deal of space, and it would also make the program more readable. Also, having only one copy of the code makes it easier to make changes. Would you rather make forty little changes scattered all throughout a potentially large program, or one change to the function body? 

When the programmer actually defines the function, it will begin with the prototype, minus the semi-colon. Then there should always be a block with the code that the function is to execute, just as you would write it for the main function. Any of the arguments passed to the function can be used as if they were declared in the block. Finally, end it all with a cherry and a closing brace. Okay, maybe not a cherry.

Let's look at an example program:

#include <iostream.h>

int mult ( int x, int y );

int main()
{
int x;
int y;

cout<<"Please input two numbers to be multiplied: ";
cin>> x >> y;
cin.ignore();
cout<<"The product of your two numbers is "<< mult ( x, y ) <<"\n";
cin.get();
}

int mult ( int x, int y )
{
return x * y;
}
The mult function is actually defined below main. Due to its prototype 
being above main, the compiler still recognizes it as being defined, and
so the compiler will not give an error about mult being undefined. As
long as the prototype is present, a function can be used even if there
is no definition. However, the code cannot be run without a definition
even though it will compile. The prototype and definition can be
combined into one also. If mult were defined before it is used, we could
do away with the prototype because the definition can act as a
prototype as well.



Return is the keyword used to force the function to return a value. Note
that
it is possible to have a function that returns no value. If a function
returns
void, the return statement is valid, but only if it does not have an
expression. In other words, for a function that returns void, the
statement "return;" is legal, but redundant.
Share this article :

No comments:

Post a Comment

 
Support : Creating Website | Johny Template | Mas Template
Copyright © 2011. Tutorial of Programing - All Rights Reserved
Template Modify by Creating Website
Proudly powered by Blogger