1.3. C++ First Example

[ fromfile: cppintro.xml id: example1 ]

Throughout this book we will use code examples to explain and illustrate important programming and OOP issues. Our aim in each case is to use a minimal example that will 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 obsolete or “deprecated”

2

start of function “main” which returns 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, we 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 that is available from the compilation process, we recommend using the command-line switch, -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 shown above, the optional switched argument -o execFile is provided to specify the name of the generated executable. If we omit that switch, as in the first version, the compiler will produce an executable file named a.out. In either case, if there already exists a file in the same directory with the name of our target executable (e.g., if you are recompiling), then the compiler will quietly and automatically overwrite it.

We have mentioned here just two of the most commonly used compiler switches. On a *nix system you can view the manual pages, a summary of the g++ command options and how they are used, by typing the command

man g++

On most systems these commands allow 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, our 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 the // 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, we use the preprocessor directive #include. (Section C.2) 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) 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 alternate syntax for the second.

Selection

C++ provides the usual assortment of syntax variations for selection which we discuss in Section 21.2

Iteration

We used two of the three iteration structures provided by C++ in our example. All three are discussed in Section 21.3