Functions in C++

by Shabbir on July 14, 2008

in C/C++

Functions are pieces of code, that can be executed by calling from another function. You know that a common C++ application, must have one function, that functions is int main().

So there is a statement of a function

return_type function_name(parameter1, parameter2,...)

{

// Statements

}

  • return_type, is the type that the function returns as a result (eg. int, float, string,...). It can be void, if the function doesn't return anything.
  • function_name, is the identifier of the function, we can call the function using that identifier
  • parameters, values that we give to the function to make some operations with them
  • statements, the code in the function, it is surrounded by braces

Example:

  1. #include
  2.  
  3. using namespace std;
  4.  
  5. int sum(int a, int b)
  6. {
  7. return a+b;
  8. }
  9.  
  10. int main()
  11. {
  12. int x=5;
  13. int y=6;
  14. int z=sum(x, y);
  15. cout << z << endl;
  16. }

The function expects two arguments, the first will be the value of x, the second will be the value of y. And it will return their sum.

So, we initialize two variables, x and y. And the variable z will get the value of the sum of x and y. That operation is performed by the function.

Sharing is Caring...

Leave a Comment

Previous post:

Next post:

    About the Author

  • author photo

    My Name is Shabbir Bhimani and I am developer by profession in the field of applications, web and database. Currently doing full time online marketing and like to share my experiences on how you can make money online @ CodeItWell.com. Read more ...


    See how you can get in touch with me.