1.3. C++ First Example

[ fromfile: cppintro.xml id: example1 ]

Throughout this book code examples explain and illustrate important programming and OOP issues. The aim in each case is to use a minimal example to illustrate the ideas and techniques briefly and efficiently. Example 1.1 provides a quick overview of some elementary C++ syntax.

Example 1.1. src/early-examples/example0/fac.cpp

/* Computes and prints n! for a given n.
   Uses several basic elements of C++. */

#include <iostream>                         1
int main() {                                2
    using namespace std;                    3
    // Declarations of variables
    int factArg = 0 ;                       4
    int fact(1) ;                           5
    do {                                    6
        cout << "Factorial of: ";           7
        cin >> factArg;                     8
        if ( factArg < 0 ) {
            cout << "No negative values, please!" << endl;
        }                                   9
    } while (factArg < 0) ;                 10
    int i = 2;
    while ( i <= factArg ) {                11
        fact = fact * i;
        i = i + 1;
    }                                       12
    cout << "The Factorial of " << factArg << " is: " << fact << endl;
    return 0;                               13
}                                           14

1

Standard C++ library - In older versions of C++, you might find <iostream.h> instead, but that version is regarded as "deprecated"; i.e. its use is discouraged.

2

Start of function "main" which returns an int

3

Permits us to use the symbols cin, cout, and endl without prefixing each name with std::

4

C style initialization syntax

5

C++ style initialization syntax

6

Start of "do..while" loop

7

Write to standard output

8

Read from standard input and convert to int

9

End of if block

10

if false, break out of do loop

11

Start of while loop

12

End of while block

13

When main returns 0, that normally means "no errors"

14

End of main block


On most platforms, you can compile and run this program using the ubiquitous GNU C compiler, gcc. The command to compile a C++ program is g++, which is a program that calls gcc, treats .c and .h files as C++ source files and automatically links to the C++ library.

To maximize the amount of diagnostic information available from the compilation process, use the command-line option, -Wall.

src/early-examples/example0> g++ -Wall fac.cpp
src/early-examples/example0> g++ -Wall -o execFile fac.cpp
  

-Wall enables all possible warnings about constructions that might be considered questionable even if they conform to the standard.

In the second version, the optional switch argument -o execFile is used to specify the name of the generated executable. If you omit that option, as in the first version, the compiler produces an executable file named a.out. [3] In either case, if there already exists a file in the same directory with the name of your target executable (e.g., if you are recompiling), the compiler quietly and automatically overwrites it.

These are just two of the most commonly used compiler options. On a *nix system you can view the manual page, a summary of command options and how they are used, by typing the command

     man g++
 or
     info g++

On most systems this command enables you to browse the online documentation for g++ one screen at a time. For more complete gcc documentation, visit the GNU online document center.

After it has been compiled successfully, the program can be run by typing the name of the executable file. Here is an example on a *nix platform:

src/early-examples/example0> ./a.out
Factorial of: -3
No negative values, please!
Factorial of: 5
The Factorial of 5 is: 120
src/early-examples/example0>

This short program uses several of the language elements that show up in most C++ programs.

Comments

C++ has single-line comments as in Java. Any text between // and the end of the line is a comment. C-style comment-delimiters for multiline comments can also be used. The text between /* and */ is a comment.

#include

To reuse functions, types or identifiers from libraries, use the preprocessor directive #include.[4] As in C, all preprocessor directives begin with the pound sign character # and are evaluated just before the compiler compiles your code. In this example, the included header <iostream> contains the Standard Library definitions for input/output.

using namespace

Symbols from the Standard Library (Appendix B, "Standard Headers") are all enclosed in the namespace std.

A namespace (Section 20.4) is a collection of classes, functions, and objects that can be addressed with a named prefix. The using declaration tells the compiler to add all symbols from the specified namespace (std) into the global namespace.

Declaring and Initializing Variables

Variable declarations come in three styles in C++ :

  type-expr  variableName;
  type-expr  variableName = init-expr;
  type-expr  variableName (init-expr);

In the first form, the variable might not be initialized. The third form is an alternative syntax for the second.

Selection

C++ provides the usual assortment of syntax variations for selection and control structures, which Section 19.2.2 discusses.

Iteration

Example 1.1 uses two of the three iteration structures provided by C++. Section 19.2.3 discusses all three.



[3] On windows, with mingw, it creates a file called a.exe.

[4] Discussed in Section C.2.