Home > Articles > Programming > C/C++

  • Print
  • + Share This
This chapter is from the book

Defining a Variable

You create, or define, a variable by stating its type, followed by one or more spaces, followed by the variable name and a semicolon. The variable name can be virtually any combination of letters, but cannot contain spaces. Legal variable names include x, J23qrsnf, and myAge. Good variable names tell you what the variables are for; using good names makes it easier to understand the flow of your program. The following statement defines an integer variable called myAge:

int myAge;

Remember that C++ is case sensitive, so myAge is a different variable name from MyAge. As a general programming practice, try to use names that tell you what the variable is for. Names such as myAge or howMany are much easier to understand and remember than names like xJ4 or theInt. If you use good variable names, you'll need fewer comments to make sense of your code.

Try this experiment: Guess what these pieces of programs do, based on the first few lines of code:

Example 1

main()
{
   unsigned short x;
   unsigned short y;
   unsigned int z;
   z = x * y;
}

Example 2

main ()
{
   unsigned short Width;
   unsigned short Length;
   unsigned short Area;
   Area = Width * Length;
} 

Case Sensitivity

C++ is case sensitive. In other words, uppercase and lowercase letters are considered to be different. A variable named age is different from Age, which is different from AGE.

NOTE

Some compilers allow you to turn case sensitivity off. Don't be tempted to do this; your programs won't work with other compilers, and other C++ programmers will be very confused by your code.

Many programmers prefer to use all lowercase letters for their variable names. If the name requires two words (for example, my car), there are two popular conventions: my_car or myCar. The latter form is called camel notation, because the capitalization looks something like a hump.

Keywords

Some words are reserved by C++, and you may not use them as variable names. These are keywords used by the compiler to control your program. Keywords include if, while, for, and main. Generally though, any reasonable name for a variable is almost certainly not a keyword.

Do's and Dont's

DO define a variable by writing the type, then the variable name.

DO use meaningful variable names.

DO remember that C++ is case sensitive.

DO understand the number of bytes each variable type consumes in memory, and what values can be stored in variables of that type.

DON'T use C++ keywords as variable names.

DON'T use unsigned variables for negative numbers.

  • + Share This
  • 🔖 Save To Your Account