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 a programmer have the choice and usually the need to compose your own functions. Listing 2.4 is a simple application that uses a function to display statements on the screen using std::cout with various parameters.
Listing 2.4. 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
Listing 2.5. Using the Return Value of a Function
1: #include <iostream> 2: using namespace std; 3: 4: // Function declaration and definition 5: int DemoConsoleOutput() 6: { 7: cout << "This is a simple string literal" << endl; 8: cout << "Writing number five: " << 5 << endl; 9: cout << "Performing division 10 / 5 = " << 10 / 5 << endl; 10: cout << "Pi when approximated is 22 / 7 = " << 22 / 7 << endl; 11: cout << "Pi more accurately is 22 / 7 = " << 22.0 / 7 << endl; 12: 13: return 0; 14: } 15: 16: int main() 17: { 18: // Function call with return used to exit 19: return DemoConsoleOutput(); 20: }
Functions can take parameters, can be recursive, can contain multiple return statements, can be overloaded, can be expanded in-line by the compiler, and lots more. These concepts are introduced in greater detail in Lesson 7, “Organizing Code with Functions.”