C/C++ Variables & Types

by Matthew Martin
Contents
Variables
Must Have A Type
Basic
C/C++ Types
Structures
Declaring
Variables
Variable
Initialisation

top
of page
Variables are used to hold values. This is related to simple algebra,
for example:
x = 2y + z
The letters x, y, and z are called algebraic terms and are used to represent
values. Each of the algebraic terms may be replaced by a value. In programming,
the terms are called variables and may not just hold numeric values but
text and other things as well. The names of variables may be letters (like
algebraic terms) but more commonly more meaningful names are used. Typical
variable names include UserEntry, i and Count.
top
of page

Variables Must Have a Type
Variables must have a type. The type refers to the type of values that
the variable may hold. The type determines the maximum and minimum values
for numeric data and in the case of strings the maximum length the string
may be limited. Once a variable has been assigned a type it may not be
changed (although in C and C++ type casting can be performed to address
these issues), so it is important to choose the correct type for your
variables.
top
of page

Basic C/C++ Types
There are a range of types available in C and C++, The basic types are
listed below.
Type |
Value Range |
Notes |
Char |
A-Z, a-z, 0-9 |
Characters. |
Int |
-32767 to 32767 |
Integers |
Float |
6 digits |
Floating point (decimal) values. |
Double |
10 digits |
Floating point with greater precision. |
Boolean |
True (non-zero) or False (0) |
Boolean logical values. |
The above table does not contain the complete list of types available,
only the basic types are shown.
Structures
Structures are a special case of using variables, declared using the keyword
struct. In C++ this is a simple class with all members of the class public.
Structures will be dealt with later when classes are considered in more
detail.
top
of page

Declaring Variables
Variables must be declared before they can be used. Declaration of variables
takes the following form:
type variablename;
e.g.:
float answer;
A number of variables of the same type can be declared in a single line
by separating them with commas. e.g.:
int, x, y, z;
top
of page

Variable Initialisation
Variables may be initialised by providing a value for the variable.
e.g.:
int count = 99;

by Matthew
Martin |