Monday, March 26, 2012

Variable Types and Declaring Variables

Variable Types

A variable type is a description of the kind of information a variable will store. Programming languages vary regarding how strict they require you to be when declaring a variable's type. Some languages, like Perl, do not require you to announce the type of a variable. Other languages require you to declare some variables as numbers and others as text-strings, for example. C++, a strongly-typed language, requires you to be even more specific than that. Instead of declaring a variable as a number, you must say whether it will store integers or decimals. In C++, the type of an integer is int and the type of a decimal is float (floating-point number).

Declaring Variables

Declaring a variable in C++ is simple. Let's say you want to declare a variable of type int called myAge. That is to say, the variable myAge will store an integer. In C++, this is written:
int myAge;
All this does is tell the computer that you plan to use an integer, and that the integer's name is myAge. In some languages, variables are initialized to 0 - that is, a variable's initial value will be 0. This is not true of C++! Sometimes your variables will be initialized to 0, but sometimes they will be initialized with garbage. As you might anticipate, this can cause some nasty bugs. Let's take a look at another sample program.
#include <iostream.h>

int main() {
  int myAge;
  cout << "My age is " << myAge << endl;
  return 0;
}
You might expect the program to output "My age is 0". In fact, the output of this program is unreliable. On one system you may get output of "My age is 11"; another system may output "My age is 0"; yet another system may output "My age is 3145". That's what it means to have a variable initialized with garbage. It is always a good idea to initialize your variables with some value. If you don't know what a variable's initial value should be, initialize it to 0. Initializing a variable is easy. Let's fix the above program so that it always outputs "My age is 22". The first line of the main function initializes myAge by assigning it a value immediately.
#include <iostream.h>

int main() {
  int myAge = 22;
  cout << "My age is " << myAge << endl;
  return 0;
}
That's all there is to it! By the way, the equals sign ("=") is called an operator and will be covered later in Section 3.

No comments:

Post a Comment