#36 ANATOMY OF A C++ PROGRAM
C++ programs are organised into classes comprising of member functions and member variables. A simple HelloWorld.cpp
like below can be classified into two parts: the preprocessor directives which start with #
and the main program that starts with int main()
1 2 3 4 5 6 7 |
#include <iostream> int main() { std::cout << "Hello World" << std::endl; return 0; } |
A preprocessor is a tool that runs before the actual compilation starts. Preprocessor directives are commands to the preprocessor that always start with the #
symbol. A custom header created by the programmer will be encapsulated by quotes "..."
instead of brackets <...>
which are typically used when including standard headers.
Custom: #include "...relative path to file\file.h"
Typical: #include <file.h>
After the preprocessor directive(s) is the body of the program characterized by the function main()
. It’s a standard convention that function main()
is declared with an int
preceding it. int
is the return value type.
Functions in C++ need to return a value unless specifically specified otherwise. In main()
an int
is always returned since it is indeed a function. This is very useful since it provides the ability to query on the returned value of the application. A typical success return value is 0
and in the event of an error -1
is returned.
Namespaces are names given to parts of code in order to reduce naming conflicts. By invoking std::cout
, you are telling the compiler to use that one unique cout
that is available in the std namespace.
C++ has two comment styles:
//
indicates the start of a line and is valid to the end of that line.
/* followed by */
indicates the contained text is a comment.
Functions enable you to divide the content of your application into functional units that can be invoked in a sequence of your choosing. In a C++ console application main()
is the starting function of your application.
Example of using functions in C++:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
#include <iostream> using namespace std; //Declare the functions int Demo_1(); int Demo_2(); int main() { Demo(); Print(); return 0; } int Demo_1() { //subtraction int x = 8; int y = 6; cout << x-y << endl; return 0; } int Demo_2() { //addition int x = 8; int y = 6; cout << x+y << endl; return 0; } |