Forum
101

C++ Level 2

Data Types, Variables and Constants

Introduction

Data Types

Literals & Constants

Variables and Variable Declaration

Extension Work

Introduction

This tutorial covers data types, literal and symbolic constants and variables.

Data Types

Imagine you are filling in a form.  Perhaps you have to type in your name, your age and your massive bank balance.  The information or data you are entering is of different types.  Your age is a number, while your name is a sequence of characters.   Age is a different data type to name.

In C++ and other programming languages, we have to be aware of different data types.  The table below lists the data types recognized by C++.

 Type bytes Range of Values Integer Types unsigned short int 2 0 to 65,535 short int 2 -32,768 to 32,768 unsigned int (16 bit) 2 0 to 65,535 int (16 bit) 2 -32,768 to 32,768 unsigned int (32 bit) 2 0 to 4,294, 967,295 int (32 bit) 4 -2,147,483,648 to 2,147,483,647 unsigned long int 4 0 to 4,294,967,295 long int 4 -2,147,483,648 to 2,147,483,648 Real Types float 4 +/- 3.4 E+38 to +/- 1.2 E-38 double 8 +/- 1.8 E+308 to +/-2.2 E-308 Non Numeric Types char 1 256 different characters possible

We can see that there are quite a few different data types. Particularly, there are many different sizes of integers.   The size is platform dependent. If, for example you are working a 32-bit system then the integer data types highlighted in red will be the default.

Note: The word unsigned means that the data type does NOT include negative numbers.

Integers

Integers are whole numbers such as 100, -20 But C++ likes us to be a bit more specific about our integers.  We can have a short , an int or a long .  They are all whole numbers but each type is restricted in how small or how large the number can be.  For example, a unsigned short int can be a whole number between 0 and 256 but an int (32 bit) can have a wider range of values.

Why would C++ want to partition whole numbers like this?  Think about memory allocation.  Numbers take up room in memory.  The larger the number the more memory space it would take up.  An unsigned short int takes up 2 bytes of memory but an int (32 bit)takes up 4 bytes.

You will see later that when we use variables, we specify the data type of the variable and we always choose the data type that will take up the least amount of room in memory.  For example, if I know that a variable will only have to hold a number between 1 and a 65,535, I would tell C++ the variable was going to hold a unsigned short int data type.  Then C++ would allocate 2 bytes of memory for that variable.

Real numbers

Real numbers are numbers with a decimal part like 10.50, -0.0635.  Again, C++ likes us to be more specific about our real numbers.  We can have a float or a double.  A double can be a much larger or much smaller real number than a float.  A float takes up 4 bytes of memory while a double takes up 8 bytes of memory.

Non numeric Types

A character is a non-numeric data types.  'a' and '5' are examples of characters.  You can combine characters into strings too. " I am a string" is an example of a string.

Note: --  a character is specified by surrounding it with the single quote symbol ' and a string is specified by surrounding it with double quote marks ".

Literals & Symbolic Constants

C++ has two types of constants: literal and symbolic. A literal constant is a value typed directly into your program wherever it is needed. A symbolic constant is also has a fixed value but we give that value a name.

Literals

Most programming makes use of literals:- a fixed numeric or non-numeric value.  When we use literals, the value is fixed in our code.  Look at the example code below.  How many literal values can you spot?

 #include int main() {   cout << "Hello " << "there.\n";   cout << "I am a";   cout << "string literal";   return 0; } Output Hello there I am a string literal

The code above has four literals of the string type:-  "Hello ", "there.", "I am a" and  "string literal"

We can use numeric literals too.  An integer literal would be a whole number such as 0, 100, -2000, etc.  A real number may be given in fixed or floating point notation such as 3.14 or 0.34E01.

Can you spot the numeric literals in the code below?

 cout << 100 << endl; cout << 3.14 << endl; Output 100 3.14

Symbolic Constants

What is a constant?  Imagine you are using a literal value in your code over and over again.  As an example consider the following:

 cout << "My value of PI is 3.14" << endl; cout << "The area of a circle is 3.14 * radius^2";

I have used the literal value 3.14 more than once.  What if later on I decide to change that literal value to 3.141.  I would have to change my code twice in this case.  It would be even more tedious if my code had lots more references to the literal value  3.14.  Imagine 10 or 20 or more references - I would have to change each one.

A convenient way around this is to create a constant.  Examine the following code;

 #define PI 3.14 cout << "My value of PI is" << PI << endl; cout << "The area of a circle is " << PI << " * radius^2";

This produces the same output as the original code.  The difference is in the line

#define PI 3.14

The #define directive tells C++ that I want to create a constant value.  The name of my constant is PI and I have given it the value of 3.14.  In the code above every time the preprocessor comes across the constant PI in the code,  it replaces it with the value 3.14 which I assigned to PI.

What if I decide to change the value of PI  from 3.14 to 3.141?   Now I  only have to change the value once by setting PI to a different value.  Then all instances of PI in the code will have the changed value.

You must remember though - after a constant is initialized, its value CANNOT be changed elsewhere in your code. You are stuck with that initial value throughout your program.

Now, using the #define directive is becoming rather obsolete. The more modern way of declaring a variable is using the keyword const. Here is an example:-

 const float PI = 3.14; cout << "My value of PI is" << PI << endl; cout << "The area of a circle is " << PI << " * radius^2";

This is a better way to declare constants because you define the data type, this makes it easier to prevent bugs in your code.

Note: By convention, constants names are UPPERCASE, so we can identify them in our code.  C++ comes with a lot of pre-defined constants.  If you see a word in UPPERCASE, then it is probably a constant.

Variables & Variable Declaration

You can't do much with programs that just print on the screen literal values that we specify in our code.  What if we have a program that has to get some user input - say a number - and we need to do something with this number?  We don't know what the number is going to be in advance so we need something in our code that will represent this unknown number.
That's where variables come in...

What is a Variable?

• a variable can hold information for us
• a variable can hold a value given by the user (from user input)
• a variable can hold a value temporarily for us so we can use it later on in our program
• a variable is a place in memory (#important concept#)

Every variable in a program is allocated it's own space in memory.  You can imagine variables as boxes (memory locations), where...

• The box has a name, (the name we give our variable)
• The box holds a value, (the value of the variable -  which can change)

Here I have a variable called `a` which has a value of 1000 and a variable b with a value of 40 and c which does not have a value yet.  Perhaps the variable c will have an unknown value until the user runs the code and we get some user input.

Declaring a Variable

We must declare a variable before we can use it.  The declaration specifies the name of the variable and what type it is.  Some examples would be

 char ch;  int index;  float balance;  long distance; // declares the variable ch of type char          // declares the variable index of type int          // declares a floating point variable called balance // declares a variable distance of type long

The comma separator can be used to declare several variables of the same data type:

 int index, count;  float average, balance; // declares two variables of type int  // declares two floating point variables

Variables can be initialized (given a starting value) at the time they are declared by using the = sign.  We can only do this if we know the value of the variable when we declare it. E.g..

char ch = 'a';
int index = 10;
float balance = 100.56;

We don't have to give a variable a value at the time we declare it.  Once you have declared a variable, you can place a value in that variable after the declaration.

 int index index = 0;  ....... index = 10; // declares two variable // assigns the variable a value // lots more code here that does something // assigns the variable a value again

Once you place a value in a variable, you are not stuck with that value.  You can place a value in a variable more than once.  The code fragment above shows that although index was given a value of 0, later on it was given a different value of 10.

It is also possible to initialize variables using a previously defined variable.

 int x1 = 10; int x2 = x1; int x3 = x1 * x2 // declares and initializes the variable x1  // assigns the value of x1 to x2  // assigns the value of the multiple of x1 and x2 to x3

Note: --  C++ does not initialize variables for us.  This means that when you declare a variable, memory space is allocated for that variable but until we give that variable a value it could have any strange value that happens to be in that memory space already.  Make sure you initialize your variables before using them.  The compiler usually tells you if you have not initialized a variable.

Naming a Variable

You can can call your variables almost anything provided they conform to the following rules:

• the first character must be a letter, underscore _ or \$
• subsequent letters can be a letter, underscore, \$ or number.
• a variable name must not be a keyword; e.g. int, long, define, etc.

Also, by convention we name our variables so that:

• the name describes what is represented by the variable.
• the name starts with a lowercase letter.
• if a variable is made up of more than one word the second and following words have their initial letters in UPPERCASE.

Here are some good variable names - (what information would you expect to find in each one?)

The first four examples would hold numbers, the last would hold a string. Here are some bad or invalid variable names:

20birds, OXAE, m, #var

Note: C++ is case sensitive and interestRate is seen as a completely different variable identifier from InterestRate.

Why Declare a Variable?

Why do we have to declare variables.  There are two good reasons.

The first is to tell C++ the data type the variable is going to hold.  The variable will then be allocated enough memory to hold that data type.  If you declare a variable with a certain data type and subsequently assign the wrong data type to that variable, you will either get a compiler error or a run-time error which may crash your program.  E.g.
 int index; index = 10.3; // declares the variable  // assigns a floating point value to index - INCORRECT

The code above may cause the compiler to complain but it will allow it. The whole number part of 10.3 would be assigned to index and the .3 decimal part would be dropped.

 char ch; ch = "Hello"; // declares the variable  // assigns a string value to ch - INCORRECT

This time, the compiler would do more than complain. It would indicate an error. Why? Well ch is declared as a char and you are trying to write a string value into it. ch only has enough room for one character, not a whole string of them.

The second reason to declare variables is to catch syntax errors, (errors in our written code). Here is an example:

 int index, num; inex = 2; num = inex; // declares the variables  // assigns a value  // assign a value to num

I have misspelled index on the second line.  If variable declaration was not required, then another variable called inex might be created.  My program would run incorrectly.  However, because variable declaration is required, the compiler would tell me that inex is not declared.  Then I would spot the misspelling and correct my code.

Extension Work

Carry out the following exercises:-

1. Create a new program and type in the code shown below. Your program should calculate the area of three rectangle. I have included code for getting the width input from a user. Complete the code as follows...

.. declare a variable for the height
.. get the height from the user using cin
.. calculate the area of 3 rectangles. Make sure you use the NUMRECTS contant.
.. output the area of the rectangle to the user using cout.
.. when everything works properly, change the constant declaration to use the more
modern const statement instead of the #define directive.
 #include #define NUMRECTS 3 void main() {   float width;   cout << "Enter a width" << endl;   cin >> width; }

1. Now start step3 of the practice assignment 3

That it!
Now try the quiz questions.