Export (0) Print
Expand All

Chapter 2 Data, Variables, and Calculations, Section 1

Applies to: Visual Studio 2010

Published: April, 2010

Provided by: Ivor Horton

Book Cover

Buy This Book from Publisher

This topic contains the following sections.

  • C++ program structure

  • Namespaces

  • Variables in C++

  • Defining variables and constants

  • Basic input from the keyboard and output to the screen

  • Performing arithmetic calculations

  • Casting operands

  • Variable scope

  • What the auto keyword does

  • How to discover the type of an expression

In this chapter, you’ll get down to the essentials of programming in C++. By the end of the chapter, you will be able to write a simple C++ program of the traditional form: input-process-output. I’ll first discuss the ISO/IEC standard C++ language features, and then cover any additional or different aspects of the C++/CLI language.

As you explore aspects of the language using working examples, you’ll have an opportunity to get some additional practice with the Visual C++ Development Environment. You should create a project for each of the examples before you build and execute them. Remember that when you are defining projects in this chapter and the following chapters through to Chapter 11, they are all console applications.

Programs that will run as console applications under Visual C++ 2010 are programs that read data from the command line and output the results to the command line. To avoid having to dig into the complexities of creating and managing application windows before you have enough knowledge to understand how they work, all the examples that you’ll write to understand how the C++ language works will be console programs, either Win32 console programs or .NET console programs. This will enable you to focus entirely on the C++ language in the first instance; once you have mastered that, you’ll be ready to deal with creating and managing application windows. You’ll first look at how console programs are structured.

A program in C++ consists of one or more functions. In Chapter 1, you saw an example that was a Win32 console program consisting simply of the function main(), where main is the name of the function. Every ISO/IEC standard C++ program contains the function main(), and all C++ programs of any size consist of several functions — the main() function where execution of the program starts, plus a number of other functions. A function is simply a self-contained block of code with a unique name that you invoke for execution by using the name of the function. As you saw in Chapter 1, a Win32 console program that is generated by the Application Wizard has a main function with the name _tmain. This is a programming device to allow the name to be main or wmain, depending on whether or not the program is using Unicode characters. The names wmain and _tmain are Microsoft-specific. The name for the main function conforming to the ISO/IEC standard for C++ is main. I’ll use the name main for all our ISO/IEC C++ examples because this is the most portable option. If you intend to compile your code only with Microsoft Visual C++, then it is advantageous to use the Microsoft-specific names for main, in which case you can use the Application Wizard to generate your console applications. To use the Application Wizard with the console program examples in this book, just copy the code shown in the body of the main function in the book to _tmain.

Figure 2-1 shows how a typical console program might be structured. the execution of the program shown starts at the beginning of the function main(). From main(), execution transfers to a function input_names(), which returns execution to the position immediately following the point where it was called in main(). The sort_names() function is then called from main(), and, once control returns to main(), the final function output_names() is called. Eventually, once output has been completed, execution returns once again to main() and the program ends.

Of course, different programs may have radically different functional structures, but they all start execution at the beginning of main(). If you structure your programs as a number of functions, you can write and test each function separately. Segmenting your programs in this way gives you a further advantage in that functions you write to perform a particular task can be re-used in other programs. The libraries that come with C++ provide a lot of standard functions that you can use in your programs. They can save you a great deal of work.

Figure 2-1

Referenced Screen


You'll see more about creating and using functions in Chapter 5.

Try it Out: A Simple Program

A simple example can help you to understand the elements of a program a little better. Start by creating a new project — you can use the Ctrl+Shift+N key combination as a shortcut for this. When the dialog shown in Figure 2-2 appears, select Win32 as the project type and Win32 Console Application as the template. You can name the project Ex2_01.

Figure 2-2

Referenced Screen

If you click the OK button, you’ll see a new dialog in the form shown in Figure 2-3 that shows an overview of what the Application Wizard will generate.

If you now click Application Settings on the left of this dialog, you’ll see further options for a Win32 application displayed, as shown in Figure 2-4.

Figure 2-3

Referenced Screen
Figure 2-4

Referenced Screen

The default setting is a Console application that will include a file containing a default version of main(), but you’ll start from the most basic project structure, so choose Empty project from the set of additional options and click the Finish button. Now you have a project created, but it contains no files at all. You can see what the project contains from the Solution Explorer pane on the left of the Visual C++ 2010 main window, as shown in Figure 2-5. Because you are starting with an empty project, you need to check that the project properties are set appropriately. You can display the project properties dialog by selecting Properties from the Project menu or just pressing Alt+F7. Select Configuration in the left pane, and then General in the left pane if it is not already highlighted. In the right pane, you’ll see a list of properties, so select Character Set in the Project Defaults set. To the right of the property name, you’ll see a drop-down list, from which you should select Not Set. The default value for this property for a Win32 console implies you are going to use the Unicode character set in the application. This will cause the compiler to look for _wmain, which won’t be present. If you fail to reset this project property, then you will get an error message during the build operation because _wmain cannot be found. Having set the Character Set property, you are ready to create the program code.

Figure 2-5

Referenced Screen

You’ll start by adding a new source file to the project, so right-click Source Files in the Solution Explorer pane and select the Add  New Item. . . menu option. The Add New Item dialog, similar to that shown in Figure 2-6, displays.

Figure 2-6

Referenced Screen

Make sure the C++ File(.cpp) template is highlighted by clicking on it, and enter the file name, as shown in Figure 2-6. The file will automatically be given the extension .cpp, so you don’t have to enter the extension. There is no problem having the name of the file the same as the name of the project. The project file will have the extension .vcxproj, so that will differentiate it from the source file.

Click the Add button to create the file. You can then type the following code in the Editor pane of the IDE window:

// Ex2_01.cpp
// A Simple Example of a Program
#include <iostream>
using std::cout;
using std::endl;
int main()
   int apples, oranges;                     // Declare two integer variables
   int fruit;                               // ...then another one
   apples = 5; oranges = 6;                 // Set initial values
   fruit = apples + oranges;                // Get the total fruit
   cout << endl;                            // Start output on a new line
   cout << "Oranges are not the only fruit... " << endl
        << "- and we have " << fruit << " fruits in all.";
   cout << endl;                            // Output a new line character
   return 0;                                // Exit the program

The preceding example is intended to illustrate some of the ways in which you can write C++ statements and is not a model of good programming style.

The editor will check the code as you type. Anything it thinks is not correct will be underlined with a red squiggle, so look out for these. If you see one, it usually means that you have mistyped something somewhere.

Since the file is identified by its extension as a file containing C++ code, the keywords in the code that the editor recognizes will be colored to identify them. You will be able to see if you have entered Int where you should have entered int, because Int will not have the color used to highlight keywords in your source code.

If you look at the Solution Explorer pane (press Ctrl+Alt+L to display it) for your new project, you’ll see the newly created source file. Solution Explorer will always show all the files in a project. You can display the Class View pane by selecting from the View menu or by pressing Ctrl+Shift+C. This consists of two panes, the upper pane showing global functions and macros within the project (and classes when you get to create a project involving classes), and the lower pane presently empty. The main() function will appear in the lower pane if you select Global Functions and Variables in the upper Class View pane; this is shown in Figure 2-7. I’ll consider what this means in more detail later, but essentially, globals are functions and/or variables that are accessible from anywhere in the program.

Figure 2-7

Referenced Screen

You can display the Property Manager pane by selecting from the View menu. If you extend the items in the tree that is displayed by clicking the [unfilled] symbols, it will look like Figure 2-8.

Figure 2-8

Referenced Screen

This shows the two possible versions you can build, the Debug version for testing and the Release version when your program has been tested. The properties for each version of the project are shown, and double-clicking on any of them will display a dialog showing the Property Pages, where you can change properties, if necessary.

You have three ways to compile and link the program; you can select the Build Ex2_01 menu item from the Build menu, you can press the F7 function key, or you can select the appropriate toolbar button — you can identify what a toolbar button does by hovering the mouse cursor over it. If there is no toolbar button that shows the tooltip Build Ex2_01 when the cursor is over it, then the Build toolbar is not currently displayed. You can remedy this by right-clicking on an empty part of the toolbar area and selecting Build from the list of toolbars that is displayed. It’s a very long list and you will probably want to choose different sets of toolbars to be displayed, depending on what you are doing.

Assuming the build operation was successful, you can execute the program by pressing the Ctrl+F5 keys or by selecting Start Without Debugging from the Debug menu. You should get the following output in a command line window:

Oranges are not the only fruit...
- and we have 11 fruits in all.
Press any key to continue ...

The first two lines were produced by the program, and the last line indicates how you can end the execution and close the command-line window. I won’t show this last line of output from other console examples, but it’s always there.

Program Comments

The first two lines in the program are comments. Comments are an important part of any program, but they’re not executable code — they are there simply to help the human reader. All comments are ignored by the compiler. On any line of code, two successive slashes // that are not contained within a text string (you’ll see what text strings are later) indicate that the rest of the line is a comment.

You can see that several lines of the program contain comments as well as program statements. You can also use an alternative form of comment bounded by /* and */. For example, the first line of the program could have been written:

/*   Ex2_01.cpp   */

The comment using // covers only the portion of the line following the two successive slashes, whereas the /*...*/ form defines whatever is enclosed between the /* and the */ as a comment, and this can span several lines. For example, you could write:

   A Simple Program Example

All four lines are comments and are ignored by the compiler. If you want to highlight some particular comment lines, you can always embellish them with a frame of some description:

 *  Ex2-01.cpp               *
 *  A Simple Program Example *

As a rule, you should always comment your programs comprehensively. The comments should be sufficient for another programmer or you at a later date to understand the purpose of any particular piece of code and how it works. I will often use comments in examples to explain in more detail than you would in a production program.

The #include Directive — Header Files

Following the comments, you have a #include directive:

#include <iostream>

This is called a directive because it directs the compiler to do something — in this case, to insert the contents of the file, iostream, that is identified between the angled brackets, <>, into the program source file before compilation. The iostream file is called a header file because it’s invariably inserted at the beginning of a program file. The iostream header file is part of the standard C++ library, and it contains definitions that are necessary for you to be able to use C++ input and output statements. If you didn’t include the contents of iostream into the program, it wouldn’t compile, because you use output statements in the program that depend on some of the definitions in this file. There are many different header files provided by Visual C++ that cover a wide range of capabilities. You’ll be seeing more of them as you progress through the language facilities.

The name of the file to be inserted by a #include directive does not have to be written between angled brackets. The name of the header file can also be written between double quotes, thus:

#include "iostream"

The only difference between this and the version above between angled brackets is the places where the compiler is going to look for the file.

If you write the header file name between double quotes, the compiler searches for the header file first in the directory that contains the source file in which the directive appears. If the header file is not there, the compiler then searches the directories where the standard header files are stored.

If the file name is enclosed between angled brackets, the compiler only searches the directories it expects to find the standard header files. Thus, when you want to include a standard header in a source, you should place the name between angled brackets because they will be found more quickly. When you are including other header files, typically ones that you create yourself, you should place the name between double quotes; otherwise, they will not be found at all.

A #include statement is one of several available preprocessor directives, and I’ll be introducing more of these as you need them throughout the book. The Visual C++ editor recognizes preprocessor directives and highlights them in blue in your edit window. Preprocessor directives are commands executed by the preprocessor phase of the compiler that executes before your code is compiled into object code, and preprocessor directives generally act on your source code in some way before it is compiled. They all start with the # character.

Namespaces and the Using Declaration

As you saw in Chapter 1, the standard library is an extensive set of routines that have been written to carry many common tasks: for example, dealing with input and output, and performing basic mathematical calculations. Since there are a very large number of these routines, as well as other kinds of things that have names, it is quite possible that you might accidentally use the same name as one of the names defined in the standard library for your own purposes. A namespace is a mechanism in C++ for avoiding problems that can arise when duplicate names are used in a program for different things, and it does this by associating a given set of names, such as those from the standard library, with a sort of family name, which is the namespace name.

Every name that is defined in code that appears within a namespace also has the namespace name associated with it. All the standard library facilities for ISO/IEC C++ are defined within a namespace with the name std, so every item from this standard library that you can access in your program has its own name, plus the namespace name, std, as a qualifier. The names cout and endl are defined within the standard library so their full names are std::cout and std::endl, and you saw these in action in Chapter 1. The two colons that separate the namespace name from the name of an entity form an operator called the scope resolution operator, and I’ll discuss other uses for this operator later on in the book. Using the full names in the program will tend to make the code look a bit cluttered, so it would be nice to be able to use their simple names, unqualified by the namespace name, std. The two lines in our program that follow the #include directive for iostream make this possible:

using std::cout;
using std::endl;

These are using declarations that tell the compiler that you intend to use the names cout and endl from the namespace std without specifying the namespace name. The compiler will now assume that wherever you use the name cout in the source file subsequent to the first using declaration, you mean the cout that is defined in the standard library. The name cout represents the standard output stream that, by default, corresponds to the command line, and the name endl represents the newline character.

You’ll learn more about namespaces, including how you define your own namespaces, a little later this chapter.

The main() Function

The function main() in the example consists of the function header defining it as main() plus everything from the first opening curly brace ({) to the corresponding closing curly brace (}). The braces enclose the executable statements in the function, which are referred to collectively as the body of the function.

As you’ll see, all functions consist of a header that defines (among other things) the function name, followed by the function body that consists of a number of program statements enclosed between a pair of braces. The body of a function may contain no statements at all, in which case, it doesn’t do anything.

A function that doesn’t do anything may seem somewhat superfluous, but when you’re writing a large program, you may map out the complete program structure in functions initially, but omit the code for many of the functions, leaving them with empty or minimal bodies. Doing this means that you can compile and execute the whole program with all its functions at any time and add detailed coding for the functions incrementally.

Program Statements

The program statements making up the function body of main() are each terminated with a semicolon. It’s the semicolon that marks the end of a statement, not the end of the line. Consequently, a statement can be spread over several lines when this makes the code easier to follow, and several statements can appear in a single line. The program statement is the basic unit in defining what a program does. This is a bit like a sentence in a paragraph of text, where each sentence stands by itself in expressing an action or an idea, but relates to and combines with the other sentences in the paragraph in expressing a more general idea. A statement is a self-contained definition of an action that the computer is to carry out, but that can be combined with other statements to define a more complex action or calculation.

The action of a function is always expressed by a number of statements, each ending with a semicolon. Take a quick look at each of the statements in the example just written, just to get a general feel for how it works. I will discuss each type of statement more fully later in this chapter.

The first statement in the body of the main() function is:

int apples, oranges;           // Declare two integer variables

This statement declares two variables, apples and oranges. A variable is just a named bit of computer memory that you can use to store data, and a statement that introduces the names of one or more variables is called a variable declaration. The keyword int in the preceding statement indicates that the variables with the names apples and oranges are to store values that are whole numbers, or integers. Whenever you introduce the name of a variable into a program, you always specify what kind of data it will store, and this is called the type of the variable.

The next statement declares another integer variable, fruit:

   int fruit;                               // ...then another one

While you can declare several variables in the same statement, as you did in the preceding statement for apples and oranges, it is generally a good idea to declare each variable in a separate statement on its own line, as this enables you to comment them individually to explain how you intend to use them.

The next line in the example is:

apples = 5; oranges = 6;       // Set initial values

This line contains two statements, each terminated by a semicolon. I put this here just to demonstrate that you can put more than one statement in a line. While it isn’t obligatory, it’s generally good programming practice to write only one statement on a line, as it makes the code easier to understand. Good programming practice is about adopting approaches to coding that make your code easy to follow, and minimize the likelihood of errors.

The two statements in the preceding line store the values 5 and 6 in the variables apples and oranges, respectively. These statements are called assignment statements, because they assign a new value to a variable, and the = is the assignment operator.

The next statement is:

fruit = apples + oranges;      // Get the total fruit

This is also an assignment statement, but is a little different because you have an arithmetic expression to the right of the assignment operator. This statement adds together the values stored in the variables apples and oranges and stores the result in the variable fruit.

The next three statements are:

cout << endl;               // Start output on a new line
cout << "Oranges are not the only fruit... " << endl
     << "- and we have " << fruit << " fruits in all.";
cout << endl;               // Start output on a new line

These are all output statements. The first statement is the first line here, and it sends a newline character, denoted by the word endl, to the command line on the screen. In C++, a source of input or a destination for output is referred to as a stream. The name cout specifies the “standard” output stream, and the operator << indicates that what appears to the right of the operator is to be sent to the output stream, cout. The << operator “points” in the direction that the data flows — from the variable or string that appears on the right of the operator to the output destination on the left. Thus, in the first statement, the value represented by the name endl — which represents a newline character — is sent to the stream identified by the name cout — and data transferred to cout is written to the command line.

The meaning of the name cout and the operator << are defined in the standard library header file iostream, which you added to the program code by means of the #include directive at the beginning of the program. cout is a name in the standard library and, therefore, is within the namespace std. Without the using directive, it would not be recognized unless you used its fully qualified name, which is std::cout, as I mentioned earlier. Because cout has been defined to represent the standard output stream, you shouldn’t use the name cout for other purposes, so you can’t use it as the name of a variable in your program, for example. Obviously, using the same name for different things is likely to cause confusion.

The second output statement of the three is spread over two lines:

cout << "Oranges are not the only fruit... " << endl
     << "- and we have " << fruit << " fruits in all.";

As I said earlier, you can spread each statement in a program over as many lines as you wish if it helps to make the code clearer. The end of a statement is always signaled by a semicolon, not the end of a line. Successive lines are read and combined into a single statement by the compiler until it finds the semicolon that defines the end of the statement. Of course, this means that if you forget to put a semicolon at the end of a statement, the compiler will assume the next line is part of the same statement and join them together. This usually results in something the compiler cannot understand, so you’ll get an error message.

The statement sends the text string “Oranges are not the only fruit...” to the command line, followed by another newline character (endl), then another text string, “- and we have ”, followed by the value stored in the variable fruit, then, finally, another text string, “ fruits in all.”. There is no problem stringing together a sequence of things that you want to output in this way. The statement executes from left to right, with each item being sent to cout in turn. Note that each item to be sent to cout is preceded by its own << operator.

The third and last output statement just sends another newline character to the screen, and the three statements produce the output from the program that you see.

The last statement in the program is:

return 0;                      // Exit the program

This terminates execution of the main() function, which stops execution of the program. Control returns to the operating system, and the 0 is a return code that tells the operating system that the application terminated successfully after completing its task. I’ll discuss all these statements in more detail later.

The statements in a program are executed in the sequence in which they are written, unless a statement specifically causes the natural sequence to be altered. In Chapter 3, you’ll look at statements that alter the sequence of execution.


Whitespace is the term used in C++ to describe blanks, tabs, newline characters, form feed characters, and comments. Whitespace serves to separate one part of a statement from another and enables the compiler to identify where one element in a statement, such as int, ends and the next element begins. Otherwise, whitespace is ignored and has no effect.

For example, consider the following statement

int fruit;                     // ...then another one

There must be at least one whitespace character (usually a space) between int and fruit for the compiler to be able to distinguish them, but if you add more whitespace characters, they will be ignored. The content of the line following the semicolon is all whitespace and is therefore ignored.

On the other hand, look at this statement:

fruit = apples + oranges;      // Get the total fruit

No whitespace characters are necessary between fruit and =, or between = and apples, although you are free to include some if you wish. This is because the = is not alphabetic or numeric, so the compiler can separate it from its surroundings. Similarly, no whitespace characters are necessary on either side of the + sign, but you can include some if you want to aid the readability of your code.

As I said, apart from its use as a separator between elements in a statement that might otherwise be confused, whitespace is ignored by the compiler (except, of course, in a string of characters between quotes). Therefore, you can include as much whitespace as you like to make your program more readable, as you did when you spread an output statement in the last example over several lines. Remember that in C++, the end of a statement is wherever the semicolon occurs.

Statement Blocks

You can enclose several statements between a pair of braces, in which case, they become a block, or a compound statement. The body of a function is an example of a block. Such a compound statement can be thought of as a single statement (as you’ll see when you look at the decision-making possibilities in C++ in Chapter 3). In fact, wherever you can put a single statement in C++, you could equally well put a block of statements between braces. As a consequence, blocks can be placed inside other blocks. In fact, blocks can be nested, one within another, to any depth.


A statement block also has important effects on variables, but I will defer discussion of this until later in this chapter when I discuss something called variable scope.

Automatically Generated Console Programs

In the last example, you opted to produce the project as an empty project with no source files, and then you added the source file subsequently. If you just allow the Application Wizard to generate the project, as you did in Chapter 1, the project will contain several files, and you should explore their contents in a little more depth. Create a new Win32 console project with the name Ex2_01A, and this time, just allow the Application Wizard to finish without choosing to set any of the options in the Application Settings dialog. The project will have four files containing code: the Ex2_01A.cpp and stdafx.cpp source files, the stdafx.h header file, and the targetver.h file that specifies the earliest version of Windows that is capable of running your application. This is to provide for basic capability that you might need in a console program, and represents a working program as it stands, which does nothing. If you have a project open, you can close it by selecting the File  Close Solution item on the main menu. You can create a new project with an existing project open, in which case, the old project will be closed automatically unless you elect to add it to the same solution.

First of all, the contents of Ex2_01A.cpp will be:

// Ex2_01A.cpp : Defines the entry point for the console application.
#include "stdafx.h"
int _tmain(int argc, _TCHAR* argv[])
  return 0;

This is decidedly different from the previous example. There is a #include directive for the stdafx.h header file that was not in the previous version, and the function where execution starts is called _tmain(), not main().

The Application Wizard has generated the stdafx.h header file as part of the project, and if you take a look at the code in there, you’ll see there are three further #include directives for the targetver.h header that I mentioned earlier, plus the standard library header files stdio.h and tchar.h The old-style header stdio.h is for standard I/O and was used before the current ISO/IEC standard for C++; this covers the same functionality as the iostream header. tchar.h is a Microsoft-specific header file defining text functions. The idea is that stdafx.h should define a set of standard system include files for your project — you would add #include directives for any other system headers that you need in this file. While you are learning ISO/IEC C++, you won’t be using either of the headers that appear in stdafx.h, which is one reason for not using the default file generation capability provided by the Application Wizard.

As I already explained, Visual C++ 2010 supports wmain() as an alternative to main() whenyou are writing a program that’s using Unicode characters — wmain() being a Microsoft-specific command that is not part of ISO/IEC standard C++. In support of that, the tchar.h header defines the name _tmain so that it will normally be replaced by main, but will be replaced by wmain if the symbol _UNICODE is defined. Thus, to identify a program as using Unicode, you would add the following statement to the beginning of the stdafx.h header file:

#define _UNICODE

Actually, you don’t need to do this with the Ex2_01A project you have just created, because the Character Set project property will have been set to use the Unicode character set by default.

Now that I’ve explained all that, I’ll stick to plain old main() for our ISO/IEC C++ examples that are console applications, because this option is standard C++ and, therefore, the most portable coding approach.

A fundamental objective in all computer programs is to manipulate some data and get some answers. An essential element in this process is having a piece of memory that you can call your own, that you can refer to using a meaningful name, and where you can store an item of data. Each individual piece of memory so specified is called a variable.

As you already know, each variable will store a particular kind of data, and the type of data that can be stored is fixed when you define the variable in your program. One variable might store whole numbers (that is, integers), in which case, you couldn’t use it to store numbers with fractional values. The value that each variable contains at any point is determined by the statements in your program, and, of course, its value will usually change many times as the program calculation progresses.

The next section looks first at the rules for naming a variable when you introduce it into a program.

Naming Variables

The name you give to a variable is called an identifier or, more conveniently, a variable name. Variable names can include the letters A–z (upper- or lowercase), the digits 0–9, and the underscore character. No other characters are allowed, and if you happen to use some other character, you will typically get an error message when you try to compile the program. Variable names must also begin with either a letter or an underscore. Names are usually chosen to indicate the kind of information to be stored.

Because variable names in Visual C++ 2010 can be up to 2048 characters long, you have a reasonable amount of flexibility in what you call your variables. In fact, as well as variables, there are quite a few other things that have names in C++, and they, too, can have names of up to 2048 characters, with the same definition rules as a variable name. Using names of the maximum length allowed can make your programs a little difficult to read, and unless you have amazing keyboard skills, they are the very devil to type in. A more serious consideration is that not all compilers support such long names. If you anticipate compiling your code in other environments, it’s a good idea to limit names to a maximum of 31 characters; this will usually be adequate for devising meaningful names and will avoid problems of compiler name length constraints in most instances.

Although you can use variable names that begin with an underscore (for example, _this and _that), this is best avoided because of potential clashes with standard system variables that have the same form. You should also avoid using names starting with a double underscore for the same reason.

Examples of good variable names include the following:

  • price

  • discount

  • pShape

  • value_


8_Ball, 7Up, and 6_pack are not legal. Neither is Hash! nor Mary-Ann. This last example is a common mistake, although Mary_Ann with an underscore in place of the hyphen would be quite acceptable. Of course, Mary Ann would not be, because blanks are not allowed in variable names. Note that the variable names republican and Republican are quite different, as names are case-sensitive, so upper- and lowercase letters are differentiated. Of course, whitespace characters in general cannot appear within a name, and if you inadvertently include whitespace characters, you will have two or more names instead of one, which will usually cause the compiler to complain.

A convention that is often adopted in C++ is to reserve names beginning with a capital letter for naming classes and use names beginning with a lowercase letter for variables. I’ll discuss classes in Chapter 8.

Keywords in C++

There are reserved words in C++ called keywords that have special significance within the language. They will be highlighted with a particular color by the Visual C++ 2010 editor as you enter your program — in my system, the default color is blue. If a keyword you type does not appear highlighted, then you have entered the keyword incorrectly. Incidentally, if you don’t like the default colors used by the text editor, you can change them by selecting Options from the Tools menu and making changes when you select Environment/Fonts and Colors in the dialog.

Remember that keywords, like the rest of the C++ language, are case-sensitive. For example, the program that you entered earlier in the chapter contained the keywords int and return; if you write Int or Return, these are not keywords and, therefore, will not be recognized as such. You will see many more as you progress through the book. You must ensure that the names you choose for entities in your program, such as variables, are not the same as any of the keywords in C++.

Declaring Variables

As you saw earlier, a variable declaration is a program statement that specifies the name of a variable of a given type. For example:

int value;

This declares a variable with the name value that can store integers. The type of data that can be stored in the variable value is specified by the keyword int, so you can only use value to store data of type int. Because int is a keyword, you can’t use int as a name for one of your variables.


A variable declaration always ends with a semicolon.

A single declaration can specify the names of several variables, but as I have said, it is generally better to declare variables in individual statements, one per line. I’ll deviate from this from time to time in this book, but only in the interests of not spreading code over too many pages.

In order to store data (for example, the value of an integer), you not only need to have defined the name of the variable, you also need to have associated a piece of the computer’s memory with the variable name. This process is called variable definition. In C++, a variable declaration is also a definition (except in a few special cases, which we shall come across during the book). In the course of a single statement, we introduce the variable name, and also tie it to an appropriately sized piece of memory.

So, the statement

int value;

is both a declaration and a definition. You use the variable name value that you have declared to access the piece of the computer’s memory that you have defined, and that can store a single value of type int.


You use the term declaration when you introduce a name into your program, with information on what the name will be used for. The term definition refers to the allotment of computer memory to the name. In the case of variables, you can declare and define in a single statement, as in the preceding line. The reason for this apparently pedantic differentiation between a declaration and a definition is that you will meet statements that are declarations but not definitions.

You must declare a variable at some point between the beginning of your program and when the variable is used for the first time. In C++, it is good practice to declare variables close to their first point of use.

Initial Values for Variables

When you declare a variable, you can also assign an initial value to it. A variable declaration that assigns an initial value to a variable is called an initialization. To initialize a variable when you declare it, you just need to write an equals sign followed by the initializing value after the variable name. You can write the following statements to give each of the variables an initial value:

int value = 0;
int count = 10;
int number = 5;

In this case, value will have the value 0, count will have the value 10, and number will have the value 5.

There is another way of writing the initial value for a variable in C++ called functional notation. Instead of an equals sign and the value, you can simply write the value in parentheses following the variable name. So, you could rewrite the previous declarations as:

int value(0);
int count(10);
int number(5);

Generally, it’s a good idea to use either one notation or the other consistently when you are initializing variables. However, I’ll use one notation in some examples and the other notation in others, so you get used to seeing both of them in working code.

If you don’t supply an initial value for a variable, then it will usually contain whatever garbage was left in the memory location it occupies by the previous program you ran (there is an exception to this that you will meet later in this chapter). Wherever possible, you should initialize your variables when you declare them. If your variables start out with known values, it makes it easier to work out what is happening when things go wrong. And one thing you can be sure of — things will go wrong.

The sort of information that a variable can hold is determined by its data type. All data and variables in your program must be of some defined type. ISO/IEC standard C++ provides you with a range of fundamental data types, specified by particular keywords. Fundamental data types are so called because they store values of types that represent fundamental data in your computer, essentially numerical values, which also includes characters because a character is represented by a numerical character code. You have already seen the keyword int for defining integer variables. C++/CLI also defines fundamental data types that are not part of ISO/IEC C++, and I’ll go into those a little later in this chapter.

The fundamental types fall into three categories: types that store integers, types that store non-integral values — which are called floating-point types — and the void type that specifies an empty set of values or no type.

Integer Variables

Integer variables are variables that can have only values that are whole numbers. The number of players in a football team is an integer, at least at the beginning of the game. You already know that you can declare integer variables using the keyword int. Variables of type int occupy 4 bytes in memory and can store both positive and negative integer values. The upper and lower limits for the values of a variable of type int correspond to the maximum and minimum signed binary numbers, which can be represented by 32 bits. The upper limit for a variable of type int is 231–1, which is 2,147,483,647, and the lower limit is –(231), which is –2,147,483,648. Here’s an example of defining a variable of type int:

int toeCount = 10;

In Visual C++ 2010, the keyword short also defines an integer variable, this time occupying 2 bytes. The keyword short is equivalent to short int, and you could define two variables of type short with the following statements:

short feetPerPerson = 2;
short int feetPerYard = 3;

Both variables are of the same type here because short means exactly the same as short int. I used both forms of the type name to show them in use, but it would be best to stick to one representation of the type in your programs, and of the two, short is used most often.

C++ also provides the integer type, long, which can also be written as long int. Here’s how you declare variables of type long:

long bigNumber = 1000000L;
long largeValue = 0L;

Of course, you could also use functional notation when specifying the initial values:

long bigNumber(1000000L);
long largeValue(0L);

These statements declare the variables bigNumber and largeValue with initial values 1000000 and 0, respectively. The letter L appended to the end of the literals specifies that they are integers of type long. You can also use the small letter l for the same purpose, but it has the disadvantage that it is easily confused with the digit 1. Integer literals without an L appended are of type int.


You must not include commas when writing large numeric values in a program. In text you might write the number 12,345, but in your program code you must write this as 12345.

Integer variables declared as long in Visual C++ 2010 occupy 4 bytes and can have values from –2,147,483,648 to 2,147,483,647. This is the same range as for variables declared as type int.


With other C++ compilers, variables of type long (which is the same as type long int) may not be the same as type int, so if you expect your programs to be compiled in other environments, don't assume that long and int are equivalent. For truly portable code, you should not even assume that an int is 4 bytes (for example, under older 16-bit versions of Visual C++ a variable of type int was 2 bytes).

If you need to store integers of an even greater magnitude, you can use variables of type long long:

long long huge = 100000000LL;

Variables of type long long occupy 8 bytes and can store values from –9223372036854775808 to 9223372036854775807. The suffix to identify an integer constant as type long long is LL or ll, but the latter is best avoided.

Character Data Types

The char data type serves a dual purpose. It specifies a one-byte variable that you can use either to store integers within a given range, or to store the code for a single ASCII character, which is the American Standard Code for Information Interchange. You can declare a char variable with this statement:

char letter = 'A';

Or you could write this as:

char letter('A');

This declares the variable with the name letter and initializes it with the constant ‘A’. Note that you specify a value that is a single character between single quotes, rather than the double quotes used previously for defining a string of characters to be displayed. A string of characters is a series of values of type char that are grouped together into a single entity called an array. I’ll discuss arrays and how strings are handled in C++ in Chapter 4.

Because the character ‘A’ is represented in ASCII by the decimal value 65, you could have written the statement as:

char letter = 65;            // Equivalent to A

This produces the same result as the previous statement. The range of integers that can be stored in a variable of type char with Visual C++ is from –128 to 127.


The ISO/IEC C++ standard does not require that type char should represent signed 1-byte integers. It is the compiler implementer's choice as to whether type char represents signed integers in the range –128 to +127 or unsigned integers in the range 0 to 255. You need to keep this in mind if you are porting your C++ code to a different environment.

The type wchar_t is so called because it is a wide character type, and variables of this type store 2-byte character codes with values in the range from 0 to 65,535. Here’s an example of defining a variable of type wchar_t:

wchar_t letter = L'Z';       // A variable storing a 16-bit character code

This defines a variable, letter, that is initialized with the 16-bit code for the letter Z. The L preceding the character constant, ‘Z’, tells the compiler that this is a 16-bit character code value. A wchar_t variable stores Unicode code values.

You could have used functional notation here, too:

wchar_t letter(L'Z');        // A variable storing a 16-bit character code

You can also use hexadecimal constants to initialize integer variables, including those of type char, and it is obviously going to be easier to use this notation when character codes are available as hexadecimal values. A hexadecimal number is written using the standard representation for hexadecimal digits: 0 to 9, and A to F (or a to f) for digits with values from 10 to 15. It’s also prefixed by 0x (or 0X) to distinguish it from a decimal value. Thus, to get exactly the same result again, you could rewrite the last statement as follows:

wchar_t letter(0x5A);        // A variable storing a 16-bit character code

Don't write decimal integer values with a leading zero. The compiler will interpret such values as octal (base 8), so a value written as 065 will be equivalent to 53 in normal decimal notation.

Notice that Windows XP, Vista, and Windows 7 provide a Character Map utility that enables you to locate characters from any of the fonts available to Windows. It will show the character code in hexadecimal and tell you the keystroke to use for entering the character. You’ll find the Character map utility if you click on the Start button and look in the System Tools folder that is within the Accessories folder.

Integer Type Modifiers

Variables of the integral types char, int, short, or long store signed integer values by default, so you can use these types to store either positive or negative values. This is because these types are assumed to have the default type modifier signed. So, wherever you wrote int or long, you could have written signed int or signed long, respectively.

You can also use the signed keyword by itself to specify the type of a variable, in which case, it means signed int. For example:

signed value = -5;           // Equivalent to signed int

This usage is not particularly common, and I prefer to use int, which makes it more obvious what is meant.

The range of values that can be stored in a variable of type char is from –128 to 127, which is the same as the range of values you can store in a variable of type signed char. In spite of this, type char and type signed char are different types, so you should not make the mistake of assuming they are the same.

If you are sure that you don’t need to store negative values in a variable (for example, if you were recording the number of miles you drive in a week), then you can specify a variable as unsigned:

unsigned long mileage = 0UL;

Here, the minimum value that can be stored in the variable mileage is zero, and the maximum value is 4,294,967,295 (that’s 232–1). Compare this to the range of –2,147,483,648 to 2,147,483,647 for a signed long. The bit that is used in a signed variable to determine the sign of the value is used in an unsigned variable as part of the numeric value instead. Consequently, an unsigned variable has a larger range of positive values, but it can’t represent a negative value. Note how a U (or u) is appended to unsigned constants. In the preceding example, I also have L appended to indicate that the constant is long. You can use either upper- or lowercase for U and L, and the sequence is unimportant. However, it’s a good idea to adopt a consistent way of specifying such values.

You can also use unsigned by itself as the type specification for a variable, in which case, you are specifying the variable to be of type unsigned int.


Remember, both signed and unsigned are keywords, so you can't use them as variable names.

The Boolean Type

Boolean variables are variables that can have only two values: a value called true and a value called false. The type for a logical variable is bool, named after George Boole, who developed Boolean algebra, and type bool is regarded as an integer type. Boolean variables are also referred to as logical variables. Variables of type bool are used to store the results of tests that can be either true or false, such as whether one value is equal to another.

You could declare the name of a variable of type bool with the statement:

bool testResult;

Of course, you can also initialize variables of type bool when you declare them:

bool colorIsRed = true;

Or like this:

bool colorIsRed(true);

You will find that the values TRUE and FALSE are used quite extensively with variables of numeric type, and particularly of type int. This is a hangover from the time before variables of type bool were implemented in C++ when variables of type int were typically used to represent logical values. In this case a zero value is treated as false and a non-zero value as true. The symbols TRUE and FALSE are still used within the MFC where they represent a non-zero integer value and 0, respectively. Note that TRUE and FALSE—written with capital letters—are not keywords in C++; they are just symbols defined within the MFC. Note also that TRUE and FALSE are not legal bool values, so don't confuse true with TRUE.

Floating-Point Types

Values that aren’t integral are stored as floating-point numbers. A floating-point number can be expressed as a decimal value such as 112.5, or with an exponent such as 1.125E2 where the decimal part is multiplied by the power of 10 specified after the E (for Exponent). Our example is, therefore, 1.125 × 102, which is 112.5.


A floating-point constant must contain a decimal point, or an exponent, or both. If you write a numerical value with neither, you have an integer.

You can specify a floating-point variable using the keyword double, as in this statement:

double in_to_mm = 25.4;

A variable of type double occupies 8 bytes of memory and stores values accurate to approximately 15 decimal digits. The range of values stored is much wider than that indicated by the 15 digits accuracy, being from 1.7 × 10–308 to 1.7 × 10308, positive and negative.

If you don’t need 15 digits’ precision, and you don’t need the massive range of values provided by double variables, you can opt to use the keyword float to declare floating-point variables occupying 4 bytes. For example:

float pi = 3.14159f;

This statement defines a variable pi with the initial value 3.14159. The f at the end of the constant specifies that it is of type float. Without the f, the constant would have been of type double. Variables that you declare as float have approximately 7 decimal digits of precision and can have values from 3.4 × 10–38 to 3.4 × 1038, positive and negative.

The ISO/IEC standard for C++ also defines the long double floating-point type, which in Visual C++ 2010, is implemented with the same range and precision as type double. With some compilers, long double corresponds to a 16-byte floating-point value with a much greater range and precision than type double.

Fundamental Types in ISO/IEC C++

The following table contains a summary of all the fundamental types in ISO/IEC C++ and the range of values that are supported for these in Visual C++ 2010.


Size In Bytes

Range of Values



true or false



By default, the same as type signed char: –128 to 127. Optionally, you can make char the same range as type unsigned char.

signed char


–128 to 127

unsigned char


0 to 255



0 to 65,535



–32,768 to 32,767

unsigned short


0 to 65,535



–2,147,483,648 to 2,147,483,647

unsigned int


0 to 4,294,967,295



–2,147,483,648 to 2,147,483,647

unsigned long


0 to 4,294,967,295

long long


–9223372036854775808 to 9223372036854775807

unsigned  long long


0 to 18446744073709551615



±3.4×10±38 with approximately 7 digits accuracy



±1.7×10±308 with approximately 15 digits accuracy

long double


±1.7×10±308 with approximately 15 digits accuracy


I have already used a lot of explicit constants to initialize variables, and in C++, constant values of any kind are referred to as literals. A literal is a value of a specific type, so values such as 23, 3.14159, 9.5f, and true are examples of literals of type int, type double, type float, and type bool, respectively. The literal “Samuel Beckett” is an example of a literal that is a string, but I’ll defer discussion of exactly what type this is until Chapter 4. Here’s a summary of how you write literals of various types.


Examples of Literals

char, signed char, or unsigned char

‘A’, ‘Z’, ‘8’, ‘* ’


L’A’, L’Z’, L’8’, L’* ’


-77, 65, 12345, 0x9FE

unsigned int

10U, 64000u


-77L, 65L, 12345l

unsigned long

5UL, 999999UL, 25ul, 35Ul

long long

-777LL, 66LL, 1234567ll

unsigned long long

55ULL, 999999999ULL, 885ull, 445Ull


3.14f, 34.506F


1.414, 2.71828

long double

1.414L, 2.71828l


true, false

You can’t specify a literal to be of type short or unsigned short, but the compiler will accept initial values that are literals of type int for variables of these types, provided the value of the literal is within the range of the variable type.

You will often need to use literals in calculations within a program, for example, conversion values such as 12 for feet into inches or 25.4 for inches to millimeters, or a string to specify an error message. However, you should avoid using numeric literals within programs explicitly where their significance is not obvious. It is not necessarily apparent to everyone that when you use the value 2.54, it is the number of centimeters in an inch. It is better to declare a variable with a fixed value corresponding to your literal instead — you might name the variable inchesToCentimeters, for example. Then, wherever you use inchesToCentimeters in your code, it will be quite obvious what it is. You will see how to fix the value of a variable a little later on in this chapter.

Defining Synonyms for Data Types

The typedef keyword enables you to define your own type name for an existing type. Using typedef, you could define the type name BigOnes as equivalent to the standard long int type with the declaration:

typedef long int BigOnes;       // Defining BigOnes as a type name

This defines BigOnes as an alternative type specifier for long int, so you could declare a variable mynum as long int with the declaration:

BigOnes mynum = 0L;             // Define a long int variable

There’s no difference between this declaration and the one using the built-in type name. You could equally well use

long int mynum = 0L;            // Define a long int variable

for exactly the same result. In fact, if you define your own type name such as BigOnes, you can use both type specifiers within the same program for declaring different variables that will end up as having the same type.

Because typedef only defines a synonym for an existing type, it may appear to be a bit superficial, but it is not at all. You’ll see later that it fulfills a very useful role in enabling you to simplify more complex declarations by defining a single name that represents a somewhat convoluted type specification. This can make your code much more readable.

Variables with Specific Sets of Values

You will sometimes be faced with the need for variables that have a limited set of possible values that can be usefully referred to by labels — the days of the week, for example, or months of the year. There is a specific facility in C++ to handle this situation, called an enumeration. Take one of the examples I have just mentioned — a variable that can assume values corresponding to days of the week. You can define this as follows:

enum Week{Mon, Tues, Wed, Thurs, Fri, Sat, Sun} thisWeek;

This declares an enumeration type with the name Week and the variable thisWeek, which is an instance of the enumeration type Week that can assume only the constant values specified between the braces. If you try to assign to thisWeek anything other than one of the set of values specified, it will cause an error. The symbolic names listed between the braces are known as enumerators. In fact, each of the names of the days will be automatically defined as representing a fixed integer value. The first name in the list, Mon, will have the value 0, Tues will be 1, and so on.

You could assign one of the enumeration constants as the value of the variable thisWeek like this:

thisWeek = Thurs;

Note that you do not need to qualify the enumeration constant with the name of the enumeration. The value of thisWeek will be 3 because the symbolic constants that an enumeration defines are assigned values of type int by default in sequence, starting with 0.

By default, each successive enumerator is one larger than the value of the previous one, but if you would prefer the implicit numbering to start at a different value, you can just write:

enum Week {Mon = 1, Tues, Wed, Thurs, Fri, Sat, Sun} thisWeek;

Now, the enumeration constants will be equivalent to 1 through 7. The enumerators don’t even need to have unique values. You could define Mon and Tues as both having the value 1, for example, with the statement:

enum Week {Mon = 1, Tues = 1, Wed, Thurs, Fri, Sat, Sun} thisWeek;

As the type of the variable thisWeek is type int, it will occupy 4 bytes, as will all variables that are of an enumeration type.

Note that you are not allowed to use functional notation for initializing enumerators. You must use the assignment operator as in the examples you have seen.

Having defined the form of an enumeration, you can define another variable as follows:

enum Week nextWeek;

This defines a variable nextWeek as an enumeration that can assume the values previously specified. You can also omit the enum keyword in declaring a variable, so, instead of the previous statement, you could write:

Week next_week;

If you wish, you can assign specific values to all the enumerators. For example, you could define this enumeration:

enum Punctuation {Comma = ',', Exclamation = '!', Question = '?'} things;

Here, you have defined the possible values for the variable things as the numerical equivalents of the appropriate symbols. The symbols are 44, 33, and 63, respectively, in decimal. As you can see, the values assigned don’t have to be in ascending order. If you don’t specify all the values explicitly, each enumerator will be assigned a value incrementing by 1 from the last specified value, as in our second Week example.

You can omit the enumeration type if you don’t need to define other variables of this type later. For example:

enum {Mon, Tues, Wed, Thurs, Fri, Sat, Sun} thisWeek, nextWeek, lastWeek;

Here, you have three variables declared that can assume values from Mon to Sun. Because the enumeration type is not specified, you cannot refer to it. Note that you cannot define other variables for this enumeration at all, because you would not be permitted to repeat the definition. Doing so would imply that you were redefining values for Mon to Sun, and this isn’t allowed.

Here, you will only look at enough of native C++ input and output to get you through learning about C++. It’s not that it’s difficult — quite the opposite, in fact — but for Windows programming, you won’t need it at all. C++ input/output revolves around the notion of a data stream, where you can insert data into an output stream or extract data from an input stream. You have already seen that the ISO/IEC C++ standard output stream to the command line on the screen is referred to as cout. The complementary input stream from the keyboard is referred to as cin. Of course, both stream names are defined within the std namespace.

Input from the Keyboard

You obtain input from the keyboard through the standard input stream, cin, using the extraction operator for a stream, >>. To read two integer values from the keyboard into integer variables num1 and num2, you can write this statement:

std::cin >> num1 >> num2;

The extraction operator, >>, “points” in the direction that data flows — in this case, from cin to each of the two variables in turn. Any leading whitespace is skipped, and the first integer value you key in is read into num1. This is because the input statement executes from left to right. Any whitespace following num1 is ignored, and the second integer value that you enter is read into num2. There has to be some whitespace between successive values, though, so that they can be differentiated. The stream input operation ends when you press the Enter key, and execution then continues with the next statement. Of course, errors can arise if you key in the wrong data, but I will assume that you always get it right!

Floating-point values are read from the keyboard in exactly the same way as integers, and of course, you can mix the two. The stream input and operations automatically deal with variables and data of any of the fundamental types. For example, in the statements,

int num1 = 0, num2 = 0;
double factor = 0.0;
std::cin >> num1 >> factor >> num2;

the last line will read an integer into num1, then a floating-point value into factor, and finally, an integer into num2.

Output to the Command Line

You have already seen output to the command line, but I want to revisit it anyway. Writing information to the display operates in a complementary fashion to input. As you have seen, the standard output stream is called cout, and you use the insertion operator, <<, to transfer data to the output stream. This operator also “points” in the direction of data movement. You have already used this operator to output a text string between quotes. I can demonstrate the process of outputting the value of a variable with a simple program.

Try it Out: Output to the Command Line

I’ll assume that you’ve got the hang of creating a new empty project by adding a new source file to the project and building it into an executable. Here’s the code that you need to put in the source file once you have created the Ex2_02 project:

// Ex2_02.cpp
// Exercising output
#include <iostream>
using std::cout;
using std::endl;
int main()
   int num1 = 1234, num2 = 5678;
   cout << endl;                                // Start on a new line
   cout << num1 << num2;                        // Output two values
   cout << endl;                                // End on a new line
   return 0;                                    // Exit program

Because you have using declarations for std::cout and std::endl, you can use the unqualified stream names in the code. The first statement in the body of main() declares and initializes two integer variables, num1 and num2. This is followed by two output statements, the first of which moves the screen cursor position to a new line. Because output statements execute from left to right, the second output statement displays the value of num1 followed by the value of num2.

When you compile and execute this, you will get the output:


The output is correct, but it’s not exactly helpful. You really need the two output values to be separated by at least one space. The default for stream output is to just output the digits in the output value, which doesn’t provide for spacing successive output values out nicely so they can be differentiated. As it is, you have no way to tell where the first number ends and the second number begins.

Formatting the Output

You can fix the problem of there being no spaces between items of data quite easily, though, just by outputting a space between the two values. You can do this by replacing the following line in your original program:

cout << num1 << num2;                        // Output two values

Just substitute the statement:

cout << num1 << ' ' << num2;                 // Output two values

Of course, if you had several rows of output that you wanted to align in columns, you would need some extra capability because you do not know how many digits there will be in each value. You can take care of this situation by using what is called a manipulator. A manipulator modifies the way in which data output to (or input from) a stream is handled.

Manipulators are defined in the standard library header file iomanip, so you need to add a #include directive for it. The manipulator that you’ll use is setw(n), which will output the value that follows right-justified in a field n spaces wide, so setw(6) causes the next output value to be presented in a field with a width of six spaces. Let’s see it working.

Try it Out: Using Manipulators

To get something more like the output you want, you can change the program to the following:

// Ex2_03.cpp
// Exercising output
#include <iostream>
#include <iomanip>
using std::cout;
using std::endl;
using std::setw;
int main()
   int num1 = 1234, num2 = 5678;
   cout << endl;                                // Start on a new line
   cout << setw(6) << num1 << setw(6) << num2;  // Output two values
   cout << endl;                                // Start on a new line
   return 0;                                    // Exit program

The changes from the last example are the addition of the #include directive for the iomanip header file, the addition of a using declaration for the setw name in the std namespace, and the insertion of the setw() manipulator in the output stream preceding each value so that the output values are presented in a field six characters wide. Now you get nice, neat output where you can actually separate the two values:

   1234  5678

Note that the setw() manipulator works only for the single output value immediately following its insertion into the stream. You have to insert the manipulator into the stream immediately preceding each value that you want to output within a given field width. If you put only one setw(), it would apply to the first value to be output after it was inserted. Any following value would be output in the default manner. You could try this out by deleting the second setw(6) and its insertion operator in the example.

Another useful manipulator that is defined in the iomanip header is std::setiosflags. This enables you to have the output left-aligned in a given field width instead of right-aligned by default. Here’s how you can do that:

cout << std::setiosflags(std::ios::left);

You can also use the std::setiosflags manipulator to control the appearance of numerical output, so it is worth exploring.

Escape Sequences

When you write a character string between double quotes, you can include special character sequences called escape sequences in the string. They are called escape sequences because they allow characters to be included in a string that otherwise could not be represented in the string, and they do this by escaping from the default interpretation of the characters. An escape sequence starts with a backslash character, \, and the backslash character cues the compiler to interpret the character that follows in a special way. For example, a tab character is written as \t, so the t is understood by the compiler to represent a tab in the string, and not the letter t. Look at these two output statements:

cout << endl << "This is output.";
cout << endl << "\tThis is output after a tab.";

They will produce these lines:

This is output.
     This is output after a tab.

The \t in the second output statement causes the output text to be indented to the first tab position.

In fact, instead of using endl, you could use the escape sequence for the newline character, \n, in each string, so you could rewrite the preceding statements as follows:

cout << "\nThis is output.";
cout << "\n\tThis is output after a tab.";

Here are some escape sequences that may be particularly useful:

Escape Sequence

What It Does


Sounds a beep




Single quote








Double quote


Question mark

Obviously, if you want to be able to include a backslash or a double quote as a character to appear in a string, you must use the appropriate escape sequences to represent them. Otherwise, the backslash would be interpreted as the start of another escape sequence, and the double quote would indicate the end of the character string.

You can also use characters specified by escape sequences in the initialization of variables of type char. For example:

char Tab = '\t';               // Initialize with tab character

Because a character literal is delimited by single quote characters, you must use an escape sequence to specify a character literal that is a single quote, thus ‘\'’.

Try it Out: Using Escape Sequences

Here’s a program that uses some of the escape sequences from the table in the previous section:

// Ex2_04.cpp
// Using escape sequences
#include <iostream>
#include <iomanip>
using std::cout;
int main()
   char newline = '\n';                         // Newline escape sequence
   cout << newline;                             // Start on a new line
   cout << "\"We\'ll make our escapes in sequence\", he said.";
   cout << "\n\tThe program\'s over, it\'s time to make a beep beep.\a\a";
   cout << newline;                             // Start on a new line
   return 0;                                    // Exit program

If you compile and execute this example, it will produce the following output:

"We'll make our escapes in sequence", he said.
        The program's over, it's time to make a beep beep.

The first line in main() defines the variable newline and initializes it with a character defined by the escape sequence for a new line. You can then use newline instead of endl from the standard library.

After writing newline to cout, you output a string that uses the escape sequences for a double quote (\“) and a single quote (\'). You don’t have to use the escape sequence for a single quote here because the string is delimited by double quotes, and the compiler will recognize a single quote character as just that, and not a delimiter. You must use the escape sequences for the double quotes in the string, though. The string starts with a newline escape sequence followed by a tab escape sequence, so the output line is indented by the tab distance. The string also ends with two instances of the escape sequence for a beep, so you should hear a double beep from your PC’s speaker.

Ivor Horton’s Beginning Visual C++® 2010, Copyright © 2010 by Ivor Horton, ISBN: 978-0-470-50088-0, Published by Wiley Publishing, Inc., All Rights Reserved. Wrox, the Wrox logo, Wrox Programmer to Programmer, and related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc and/or its affiliates.

© 2014 Microsoft