CPPFunctions

Functions in C++

  • Every C++ program has at least one function, main().
  • Functions come in two varieties:
    1. 1. Built-in functions, which are part of your compiler package. A great reference are available here.
    2. User-defined functions, which are the functions you write yourself.
    Example of a User-defined function:
    Source code Result
    #include <iostream>
    // function Demonstration Function
    // prints out a useful message
    void DemonstrationFunction() {
      std::cout << "In Demonstration Function\n";
    }
    // function main - prints out a message, then
    // calls DemonstrationFunction, then prints out
    // a second message.
    int main() {
      std::cout << "In main\n" ;
      DemonstrationFunction();
      std::cout << "Back in main\n";
      return 0;
    }
    In main
    In Demonstration Function
    Back in main
    
    

    You can download this example here (needed tools can be found in the right menu on this page).

  • Functions return a value or they return void, meaning they do not return anything.
  • Functions consist of a header, which will be the name and any included parameter to the function, and a body, which will be the code inside the function braces.
  • Method is simply another term for functions that are part of a class.
  • Functions can be called by another function which can be called by another function and so on.
  • When a function call has returned any, statement after the call will be executed in you program.
© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the correctness in the pages or source codes.
The risk of using this web-site pages or any program codes from this website is entirely at the individual user.