Learning C-Style C++


by Direct Approach Mentoring



=

3. Assignment

Use the

=

sign to store a value in a variable.
For example, let's store the number

5

in the varible

n

:

n =

5

;



No matter what

n

was before, it is now

5

. The old value of

n

is gone forever.


Here are some more assignments for the varibles we created earlier:

char

letter;

bool

b;

float

f;


letter =
'A'
;

b =

true

;

f =

1.555

;



You can also use assignment to set the starting value of a variable.
Let's create a number called

number

and start it at

100

:

int

number =

100

;



Assignment works between variables, too. But here is the key point: Assignment only changes the value of the variable on the left side. Nothing on the right side is ever affected by assignment.

n = number;


The above line takes the value of

number

and puts it in

n

.
This means

number

itself is not changed.
Always: the computer looks to the right side of the

=

sign for a value. Then it stores this value the variable on the left side.
Which means you must always have a variable on the left side to store into.



Next: 4. Operators