Let's get started with C++

 1.0 Hello World

This program prints Hello World! to the standard output stream:

#include <iostream>

int main()

{

std::cout << "Hello World!" << std::endl;

}

Analysis

Let's examine each part of this code in detail:

  • #include <iostream> is a preprocessor directive that includes the content of the standard C++ header file iostream.

iostream is a standard library header file that contains definitions of the standard input and output

streams. These definitions are included in the std namespace, explained below.

The standard input/output (I/O) streams provide ways for programs to get input from and output to an external system -- usually the terminal.

  • int main() { ... } defines a new function named main. By convention, the main function is called upon

execution of the program. There must be only one main function in a C++ program, and it must always return

a number of the int type.

Here, the int is what is called the function's return type. The value returned by the main function is an exit code.

By convention, a program exit code of 0 or EXIT_SUCCESS is interpreted as success by a system that executes

the program. Any other return code is associated with an error.

If no return statement is present, the main function (and thus, the program itself) returns 0 by default. In this

example, we don't need to explicitly write return 0;.

All other functions, except those that return the void type, must explicitly return a value according to their return type, or else must not return at all.

  • std::cout << "Hello World!" << std::endl; prints "Hello World!" to the standard output strea

std is a namespace, and :: is the scope resolution operator that allows look-ups for objects by name

within a namespace.

There are many namespaces. Here, we use :: to show we want to use cout from the std namespace.

For more information refer to Scope Resolution Operator - Microsoft Documentation.std::cout is the standard output stream object, defined in iostream, and it prints to the standard

output (stdout).

<< is, in this context, the stream insertion operator, so called because it inserts an object into the

stream object.

The standard library defines the << operator to perform data insertion for certain data types into

output streams. stream << content inserts content into the stream and returns the same, but

updated stream. This allows stream insertions to be chained: std::cout << "Foo" << " Bar"; prints

"FooBar" to the console.

"Hello World!" is a character string literal, or a "text literal." The stream insertion operator for

character string literals is defined in file iostream.

std::endl is a special I/O stream manipulator object, also defined in file iostream. Inserting a

manipulator into a stream changes the state of the stream.

The stream manipulator std::endl does two things: first it inserts the end-of-line character and then it

flushes the stream buffer to force the text to show up on the console. This ensures that the data

inserted into the stream actually appear on your console. (Stream data is usually stored in a buffer and

then "flushed" in batches unless you force a flush immediately.)

An alternate method that avoids the flush is:

std::cout << "Hello World!\n";

where \n is the character escape sequence for the newline character.

The semicolon (;) notifies the compiler that a statement has ended. All C++ statements and class

definitions require an ending/terminating semicolon.


1.1: Comments

A comment is a way to put arbitrary text inside source code without having the C++ compiler interpret it with any functional meaning. Comments are used to give insight into the design or method of a program.

There are two types of comments in C++:

Single-Line Comments

The double forward-slash sequence // will mark all text until a newline as a comment:

int main()

{

GoalKicker.com – C++ Notes for Professionals 4

// This is a single-line comment.

int a; // this also is a single-line comment

int i; // this is another single-line comment

}

C-Style/Block Comments

The sequence /* is used to declare the start of the comment block and the sequence */ is used to declare the end of comment. All text between the start and end sequences is interpreted as a comment, even if the text is otherwise valid C++ syntax. These are sometimes called "C-style" comments, as this comment syntax is inherited from C++'s predecessor language, C:

int main()

{

/*

* This is a block comment.

*/

int a;

}

In any block comment, you can write anything you want. When the compiler encounters the symbol */, it terminates the block comment:

int main()

{

/* A block comment with the symbol /*

Note that the compiler is not affected by the second /* however, once the end-block-comment symbol is reached, the comment ends.

*/

int a;

}

The above example is valid C++ (and C) code. However, having additional /* inside a block comment might result in a warning on some compilers.

Block comments can also start and end within a single line. For example:

void SomeFunction(/* argument 1 */ int a, /* argument 2 */ int b);

Importance of Comments

  • As with all programming languages, comments provide several benefits:
  • Explicit documentation of code to make it easier to read/maintain
  • Explanation of the purpose and functionality of code
  • Details on the history or reasoning behind the code
  • Placement of copyright/licenses, project notes, special thanks, contributor credits, etc. directly in the source code.

However, comments also have their downsides:

  • They must be maintained to reflect any changes in the code
  • Excessive comments tend to make the code less readable

The need for comments can be reduced by writing clear, self-documenting code. A simple example is the use of explanatory names for variables, functions, and types. Factoring out logically related tasks into discrete functions goes hand-in-hand with this.

Comment markers used to disable code

During development, comments can also be used to quickly disable portions of code without deleting it. This is often useful for testing or debugging purposes, but is not good style for anything other than temporary edits. This is often referred to as “commenting out”.

Similarly, keeping old versions of a piece of code in a comment for reference purposes is frowned upon, as it clutters files while offering little value compared to exploring the code's history via a versioning system.


1.2: The standard C++ compilation process

Executable C++ program code is usually produced by a compiler.

A compiler is a program that translates code from a programming language into another form which is (more) directly executable for a computer. Using a compiler to translate code is called compilation.

C++ inherits the form of its compilation process from its "parent" language, C. Below is a list showing the four major steps of compilation in C++:

1. The C++ preprocessor copies the contents of any included header files into the source code file, generates macro code, and replaces symbolic constants defined using #define with their values.

2. The expanded source code file produced by the C++ preprocessor is compiled into assembly language appropriate for the platform.

3. The assembler code generated by the compiler is assembled into appropriate object code for the platform.

4. The object code file generated by the assembler is linked together with the object code files for any library functions used to produce an executable file.

  • Note: some compiled code is linked together, but not to create a final program. Usually, this "linked" code can also be packaged into a format that can be used by other programs. This "bundle of packaged, usable code" is what C++ programmers refer to as a library.

Many C++ compilers may also merge or un-merge certain parts of the compilation process for ease or for additional analysis. Many C++ programmers will use different tools, but all of the tools will generally follow this generalized process when they are involved in the production of a program.