08.01.2023 Views

Learn to Program with C_ Learn to Program using the Popular C Programming Language ( PDFDrive )

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

2.8 The Assignment Statement

Chapter 2 ■ C – The Basics

In Section 1.9, we introduced the assignment statement. Recall that an assignment statement

consists of a variable followed by an equals sign (=) followed by the value to be assigned to the

variable, followed by a semicolon. We could write this as:

<variable> = <value>;

<value> must be compatible with <variable> otherwise we will get an error. For example, if

<variable> is int, we must be able to derive an integer from <value>. And if <variable> is

double, we must be able to derive a floating-point value from <value>. If n is int and x is double,

we cannot, for instance, write

n = "Hi there"; //cannot assign string to int

x = "Be nice"; //cannot assign string to double

It is useful to think of the assignment statement being executed as follows: the value on the

right-hand side of = is evaluated. The value obtained is stored in the variable on the left-hand

side. The old value of the variable, if any, is lost. For example, if score had the value 25, then after

the statement

score = 84;

the value of score would be 84; the old value 25 is lost. We can picture this as:

A variable can take on any of several values, but only one at a time. As another example,

consider this statement:

score = score + 5;

Suppose score has the value 84 before this statement is executed. What is the value after

execution?

First, the right-hand side score + 5 is evaluated using the current value of score, 84. The

calculation gives 89—this value is then stored in the variable on the left-hand side; it happens to

be score. The end result is that the value of score is increased by 5 to 89. The old value 84 is lost.

It is possible that even though an assignment statement is valid, it could produce an error

when the program is run. Consider the following (a, b, c, d, and e are int):

a = 12;

b = 5;

c = (a – b) * 2;

d = c + e;

Each of these is a correctly formed assignment statement. However, when these statements

are executed, an error will result. Can you see how?

41

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!