Friday, May 9, 2014

Functions in C++

Functions in C++

Functions in C++ are the same as functions in C. Functions are artifacts that enable you to divide the content of your application into functional units that can be invoked in a sequence of your choosing. A function, when called (that is, invoked), typically returns a value to the calling function. The most famous function is, of course, main(). It is recognized by the compiler as the starting point of your C++ application and has to return an int (i.e., an integer). 

You as aprogrammer have the choice and usually the need to compose your own functions. Example 1.1 is a simple application that uses a function to display statements on the screen using std::cout with various parameters.

Example 1.1. Declaring, Defining,and Calling a Function That Demonstrates Some Capabilities of std::cout

1: #include <iostream>
2: using namespace std;
3:
4: // Function declaration
5: int DemoConsoleOutput();
6:
7: int main()
8: {
9: // Call i.e. invoke the function
10: DemoConsoleOutput();
11:
12: return 0;
13: }
14:
15: // Function definition
16: int DemoConsoleOutput()
17: {
18: cout << “This is a simple string literal” << endl;
19: cout << “Writing number five: “ << 5 << endl;
20: cout << “Performing division 10 / 5 = “ << 10 / 5 << endl;
21: cout << “Pi when approximated is 22 / 7 = “ << 22 / 7 << endl;
22: cout << “Pi more accurately is 22 / 7 = “ << 22.0 / 7 << endl;
23:
24: return 0;
25: }
Output:
This is a simple string literal
Writing number five: 5
Performing division 10 / 5 = 2
Pi when approximated is 22 / 7 = 3
Pi more accurately is 22 / 7 = 3.14286

No comments:

Post a Comment