Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- A function declaration is shown below. This example has a return type of void, indicating that
- the function does not provide a result to the caller. The caller must provide two arguments for the
- function to work with — an integer and a character.
- void myFunction(int i, char c);
- Without an actual defi nition to match this function declaration, the link stage of the compilation
- process will fail because code that makes use of the function myFunction() will be calling
- nonexistent code. The following defi nition prints the values of the two parameters.
- void myFunction(int i, char c)
- {
- std::cout << “the value of i is “ << i << std::endl;
- std::cout << “the value of c is “ << c << std::endl;
- }
- Elsewhere in the program, you can make calls to myFunction() and pass in constants or variables
- for the two parameters. Some sample function calls are shown here:
- myFunction(8, ‘a’);
- myFunction(someInt, ‘b’);
- myFunction(5, someChar);
- In C++, unlike C, a function that takes no parameters just has an empty
- parameter list. It is not necessary to use void to indicate that no parameters are
- taken. However, you should still use void to indicate when no value is returned.
- C++ functions can also return a value to the caller. The following function declaration and
- defi nition is for a function that adds two numbers and returns the result.
- int addNumbers(int number1, int number2);
- int addNumbers(int number1, int number2)
- {
- int result = number1 + number2;
- return result;
- }
- In C++11, every function has a local predefi ned variable __func__ that looks as follows:
- static const char __func__[] = “function-name”;
- This variable can for example be used for logging purposes:
- int addNumbers(int number1, int number2)
- {
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement