Home > Articles > Programming > C/C++

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

Assigning Values to Your Variables

You assign a value to a variable by using the assignment operator (=). Thus, you would assign 5 to Width by writing

unsigned short Width;
Width = 5;


long is a shorthand version of long int, and short is a shorthand version of short int.

You can combine these steps and initialize Width when you define it by writing

unsigned short Width = 5;

Initialization looks very much like assignment, and with integer variables, the difference is minor. Later, when constants are covered, you will see that some values must be initialized because they cannot be assigned to. The essential difference is that initialization takes place at the moment you create the variable.

Just as you can define more than one variable at a time, you can initialize more than one variable at creation. For example:

// create two long variables and initialize them
long width = 5, length = 7;

This example initializes the long integer variable width to the value 5 and the long integer variable length to the value 7. You can even mix definitions and initializations:

int myAge = 39, yourAge, hisAge = 40;

This example creates three type int variables, and it initializes the first and third.

Listing 3.2 shows a complete program, ready to compile, that computes the area of a rectangle and writes the answer to the screen.

Listing 3.2  A Demonstration of the Use of Variables

  0:  // Demonstration of variables
  1:  #include <iostream>
  3:  int main()
  4:  {
  5:     using std::cout;
  6:     using std::endl;
  8:     unsigned short int Width = 5, Length;
  9:     Length = 10;
 11:     // create  an unsigned short and initialize with result
 12:     // of multiplying Width by Length
 13:     unsigned short int Area  = (Width * Length);
 15:     cout << "Width:" << Width << "\n";
 16:     cout << "Length: "  << Length << endl;
 17:     cout << "Area: " << Area << endl;
 18:     return 0;
 19:  }


Length: 10
Area: 50

Analysis Line 1 includes the required include statement for the iostream's library so that cout will work. Line 3 begins the program. Lines 5 and 6 define cout and endl as being part of the standard (std) namespace.

On line 8, Width is defined as an unsigned short integer, and its value is initialized to 5. Another unsigned short integer, Length, is also defined, but it is not initialized. On line 9, the value 10 is assigned to Length.

On line 13, an unsigned short integer, Area, is defined, and it is initialized with the value obtained by multiplying Width times Length. On lines 15-17, the values of the variables are printed to the screen. Note that the special word endl creates a new line.

  • + Share This
  • 🔖 Save To Your Account