2.3. Variables

One of the most powerful features of a programming language is the ability to manipulate variables. A variable is a named location that stores a value.

Just as there are different types of values (integer, character, etc.), there are different types of variables. When you create a new variable, you have to declare what type it is.

Note

In C++, integer variables are declared as type int and character variables are declared as type char.

The following statement creates a new variable named fred that has type char.

char fred;

This kind of statement is called a declaration.

The type of a variable determines what kind of values it can store. A char variable can store a character, and it should come as no surprise that int variables can store integers.

There are several types in C++ that can store string values, but we are going to skip that for now (see Chapter 7).

To create an integer variable, the syntax is

int bob;

where bob is the arbitrary name you made up for the variable. In general, you will want to make up variable names that indicate what you plan to do with the variable. For example, if you saw these variable declarations:

char first_letter;
char last_letter;
int hour, minute;

you could probably make a good guess at what values would be stored in them. This example also demonstrates the syntax for declaring multiple variables with the same type: hour and minute are both integers (int type).

Although the language allows this, it should be avoided. It is easy to accidentally create uninitialized variables, one of the most common sources of error in C++ programs. Consider the following:

What do you think this program will output?

What should it output?

Naming conventions

C++ is a multi-paradigm language with a long history. Over the years many different groups have developed different programming styles for C++. None of them are wrong as long as they apply their rules consistently.

Since this book intends to teach C++, it follows the conventions used in the C++ Standard Library. For more information about naming conventions, see the Naming conventions section of the C++ Core Guidelines, edited by Bjarne Stroustrup and Herb Sutter.

If you continue programming in C++, you will undoubtedly encounter variables that use other styles.

That’s ok. You can’t follow everyone’s conventions.

Write code that creates the variables name, first_initial, and number_of_siblings IN THAT ORDER. It is up to you to choose the correct types for these variables.


More to Explore

You have attempted of activities on this page