The C++Course provides a general introduction to programming in C++. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details. |
![]() |
Home ![]() ![]() |
||
See also: Returning from Main | ||
![]() ![]() ![]() ![]() ![]() ![]() |
||
Adding New Functions
So far we have only been using the functions that are built into C++, but it is also possible to add new functions. Actually, we have already seen one function definition: main. The function named main is special because it indicates where the execution of the program begins, but the syntax for main is the same as for any other function definition: void NAME ( LIST OF PARAMETERS ) {STATEMENTS }
main doesn't take any parameters, as indicated by the empty parentheses () in it's definition. The first couple of functions we are going to write also have no parameters, so the syntax looks like this: void newLine () {cout << endl; } This function is named newLine; it contains only a single statement, which outputs a newline character, represented by the special value endl. In main we can call this new function using syntax that is similar to the way we call the built-in C++ commands: void main (){ cout << "First Line." << endl; newLine (); cout << "Second Line." << endl; } The output of this program is First line.Second line. Notice the extra space between the two lines. What if we wanted more space between the lines? We could call the same function repeatedly: void main (){ cout << "First Line." << endl; newLine (); newLine (); newLine (); cout << "Second Line." << endl; } Or we could write a new function, named threeLine, that prints three new lines: void threeLine (){ newLine (); newLine (); newLine (); } void main () { cout << "First Line." << endl; threeLine (); cout << "Second Line." << endl; } You should notice a few things about this program:
So far, it may not be clear why it is worth the trouble to create all these new functions. Actually, there are a lot of reasons, but this example only demonstrates two:
|
||
Home ![]() ![]() |