C++ Variable Declarations

Variable Names, Types and Declarations : Variables are the objects in C++ .where data is stored, manipulated through expressions, and printed. Variables have two defining characteriestics: a name (or identifier) and a type.

Variable Name Rules: The rules for naming variables are:

  1. Variable names may only consist of alpha-numeric characters and the '_' character.
  2. Variables names must begin with an alphabetic character or the '_' character.
  3. Capitalization is meaningful. Therefore, myVar and MyVar are two distinct variables.
  4. Variables may not have the same name as a C++ keyword (see Appendix 1, pg 999).

Variable Types: There are an infinite number of allowable variable types, because C++ allows programmers to make their own types. However, there are only a few built-in types (i.e., types that are always available in C++ without any inclusions). Some built-in types are:

  1. int       - variables of this type store positive, zero, and negative integer values.
  2. double - variables of this type store values containing fractional or real values.
  3. char     - variables of this type store single characters (e.g., 'a', 'F', '$', or '!').
  4. bool     - variables of this types store one of two values: true or false.

The above are the built-in types we will use most often. Please note, they are not the only ones--that is, there are varients to these types. For example, float is another built-in type for storing real numbers, but it has less precision than the double type.

There is one other type, string,which we will use frequently. The string type is not built-in. You must include the string system definitions to get this type (i.e., have the code #include <string> appearing at the top of your program. This final type we will frequently use is:

  1. string  - variables of this type store zero or more characters (e.g., "a string" or "hello").

Variable Declarations: Before you can store information in a variable, it needs to be declared. When you declare a variable, you are identifying the variable's two defining characteristics, i.e., its type and its name (in that order). See below for some sample variable declarations. One more thing, you can also, optionally, give the variable a value when you declare it--this is called "initializing the variable."