Friday, May 22, 2009

Variables with C++

The most important part of any computer program is the program's variables. Variables are a representation of a memory address that holds a numeric value.

There are a variety of variable types you can use in C++:
  • int - Holds the value of an integer. Depending on the type, the value can range from as low as -2,147,483,648 to as high as 2,147,483,648
  • float - Holds a value of 1.2e-38 to 3.4e38
  • double - Holds a value of 2.2e-308 to 1.8e308
  • char - Holds one character.
  • bool - Holds a value of true or false (1 or 0)
Integers can also be signed or unsigned, and long or short. Signed variables can be negative or positive. Unsigned variables are always positive. Long variables are for variables which will hold considerably larger numbers. Short variables are for variables which will hold considerably smaller numbers. By default, all of the variable types are signed and long unless otherwise specified by the programmer. Note that a bool does not apply to the (un)signed, long/short classifications.

Syntax of declaring variables:

All of the following are legal ways to declare variables in C++:

unsigned short int shortstack = 128;

bool amitrue = false;

char what_letter_am_i = "Y";

float highm8 = 1.7777;

double imavaribale = 9.93;


When declaring variables, always be sure to set them to a value of something. If you can not set them to a value when you first declare them, then set them to 0 or null.

Having the user input a value of a variable with std::cin:

You can also have the user input the value of a variable by using the std::cin command which will pause the program until a value is input and the ENTER key is pressed. Two examples of this are below:

std::cin >> int anewvariable;

int anoldvariable = 0;
std::cin >> anoldvariable;


Constant Variables

In some cases in your programs, you will want to declare a variable whose value will never be changed. You can do this by placing the keyword "const" in from of your variable declaration. Several examples of this are below:

const unsigned short int avariable = 16;

const bool thisistrue = false;

const int myint = 8;

const char = "Q";

2 comments:

  1. Quote:
    "All of the following are legal ways to declare variables in C++:

    unsigned short int = 128; "

    I believe you are missing the variable's name there. The format is always

    'sign' 'length' 'type' 'name' = 'value'

    right?

    ReplyDelete