Declaration and Definition of a Function
Declaration and definition are two different things. Declaration is the prototype of the function, that includes the return type, name and argument list to the function and definition is the actual function code. Declaration of a function is also known as signature of a function. As we declare a variable like int x; before using it in our program, similarly we need to declare function before using it. Declaration and definition of a function can be combined together if we write the complete function before the calling function. Then we don’t need to declare it explicitly. If we have written all of our functions in a different file and we call these functions from mani() which is written in a defferent file. In this case, the main( ) will not be compiled unless it knows about the functions declaration. There we write the declaration of functions before the main() function. Function declaration is a one line statement in which we write the return type, name of the function and the data type of arguments. Name of the arguments is not necessary. The definition of the function contains the complete code of the function. It starts with the declaration statement with the addition that in definition, we do write the names of the arguments. After this, we write an opening brace and then all the statements, followed by a closing brace.
If the function square is defined in a separate file or after the calling function, then we need to declare it:
Double square (double);
Double square (double number)
return (my_num * my_num);
Here is the complete code to elaborate the topic more:
//Here we are declaring the function.
double num, result;
result = 0;
num = 0;
cout<<”Please Enter a Number to calculate the square of.”;
//now we are going to call the function
result = square (num);
cout <<”The square of ”<<num<<”is”<<result;
// function to calculate the square of a number
double square ( double num)
return (num * num ) ;
A function in a calling program can take place as a stand-alone statement, on hand side of a statement. This can be a part of an assignment expression.