C++ Basics of Function

October 13, 2015 Posted by WithU Technologies
Function consist of few lines of statements which are arranged in a meaningful manner to fulfill a particular task.
·         There are many functions which are predefined within Standard C++ libraries.

·         But you can also create your own functions in C++.

·         We can reuse the code within a function.

·         Without altering the program structure, we can make modification within a single function.

·         Every C++ program has at least one function – the main() function.

·         A function’s return type is declared before its name.

Syntax:

return-data-type function-name (parameter 1, parameter 2….) {

Statements

}
·         return-data-type: Datatype of the value which is to be returned.

·         function-name:  Name of the function which is to be used.

·         Parameters: In between the brackets we have to put identifiers followed by a data type, which are used within the function. Each parameter looks like a regular variable declaration and also acts within the function as a local variable which is local to the function.



Parameters are optional and thus functions are also used without any parameters.
·         Statements: Here we use block of statements which are used to define usability of function here.

Ever Function have a definite return type. As in case of main() function it returns an integer value 0, as shown below:

int main() {

      //statements     

      return 0;

}

But sometimes the function did not return any value, those functions are defined with void keyword which defines a valueless state.

#include <iostream>
using namespace std;

void displayMessage (){

  cout << "I have a message for you";

}

int main (){

  displayMessage ();

}
·         Function is always declared before its call.

·         Here we declare a void function without any parameter that just prints a line.

·         It does not carry forward with any return value to the main function.

·         Thus, the program starts with main function as always and call for displayMessage function which outputs the line ultimately.

Function declaration:

#include <iostream>
using namespace std;

//Function declaration

void displayMessage();

int main(){

      displayMessage();

}

//Function definition

void displayMessage(){

      cout<<"I have a message";

}
·         It is specially required when we use a particular function in multiple different files, thus we need to access it from an external file. In such cases we need to declare the function at the top of the file calling the function.

·         It tells the compiler about the function name and how to call it.