A Beginner's C++ Program
Sample program
#include <iostream> using namespace std; int main() { cout << "Enjoy yourself with C++!" << endl; return 0; }
A C++ program is made up of objects with their accompanying member functions and global functions, which do not belong to any single
particular class. Each function fulfills its own particular task and can also
call other functions. You can create functions yourself or use ready-made
functions from the standard library. You will always need to write the global
function main() yourself since it has a special role to
play; in fact it is the main program.
The short programming example on the opposite page demonstrates
two of the most important elements of a C++ program. The program contains only
the function main() and displays a message.
The first line begins with the number symbol, #, which indicates
that the line is intended for the preprocessor. The
preprocessor is just one step in the first translation phase and no object code
is created at this time. You can type
#include <filename>
to have the preprocessor copy the quoted file to this position in
the source code. This allows the program access to all the information contained
in the header file. The header file iostream comprises
conventions for input and output streams. The word stream
indicates that the information involved will be treated as a flow of data.
Predefined names in C++ are to be found in the std (standard) namespace. The using
directive allows direct access to the names of the std
namespace.
Program execution begins with the first instruction in function
main(), and this is why each C++ program must have a
main function. The structure of the function is shown on the opposite page.
Apart from the fact that the name cannot be changed, this function's structure
is not different from that of any other C++ function.
In our example the function main()
contains two statements. The first statement
cout << "Enjoy yourself with C++!" << endl;
outputs the text string Enjoy yourself with
C++! on the screen. The name cout (console
output) designates an object responsible for output.
The two less-than symbols, <<,
indicate that characters are being "pushed" to the output stream. Finally endl
(end of line) causes a line feed. The statement
return 0;
terminates the function main() and also
the program, returning a value of 0 as an exit code to
the calling program. It is standard practice to use the exit code 0 to indicate that a program has terminated correctly.
Note that statements are followed by a semicolon. By the way,
the shortest statement comprises only a semicolon and does
nothing.
0 Comments