14
Chapter 1
describe the switch’s
behavior. Does it toggle from one state (on) to another
state (off)?
Or is it a dimmer switch, which can be set to many different states
between on and off?
The collection of behaviors and states describing an object is called its
type. C++ is a
strongly typed language, meaning each object has a predefined
data type.
C++ has a built-in integer type called
int
. An
int
object
can store whole
numbers (its state), and it supports many math operations (its behavior).
To perform any meaningful tasks with
int
types, you’ll create some
int
objects and name them. Named objects are called
variables.
Declaring Variables
You declare variables by providing their type, followed by their name, fol-
lowed by a semicolon. The following example
declares a variable called
the_answer
with type
int
:
int
u
the_answer
v
;
The type,
int
u
, is followed by the variable name,
the_answer
v
.
Initializing a Variable’s State
When you declare variables, you initialize them.
Object initialization establishes
an object’s initial state, such as setting its value. We’ll
delve into the details of
initialization in Chapter 2. For now, you can use the equal sign (
=
) following a
variable declaration to set the variable’s initial value. For example, you could
declare and assign
the_answer
in one line:
int the_answer = 42;
After running this line of code,
you have a variable called
the_answer
with type
int
and value 42. You can assign variables equal to the result of
math expressions, such as:
int lucky_number = the_answer / 6;
This line evaluates the expression
the_answer / 6
and assigns the result
to
lucky_number
. The
int
type
supports many other operations, such as addi-
tion
+
, subtraction
-
, multiplication
*
, and modulo division
%
.
N O T E
If you aren’t familiar with modulo division or are wondering what happens when you
divide two integers and there’s a remainder, you’re asking great questions. And those
great questions will be answered in detail in Chapter 7.