08.01.2023 Views

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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

5.5 Assignment Operators

Chapter 5 ■ Programs with Repetition Logic

So far, we have used the assignment operator = to assign the value of an expression to a variable,

as in the following:

c = a + b

The entire construct consisting of the variable = and the expression is referred to as an

assignment expression. When the expression is followed by a semicolon, it becomes an assignment

statement. The value of an assignment expression is simply the value assigned to the variable.

For example, if a is 15 and b is 20, then the assignment expression

c = a + b

assigns the value 35 to c. The value of the (entire) assignment expression is also 35.

Multiple assignments are possible, as in

a = b = c = 13

The operator = evaluates from right to left, so the above is equivalent to

a = (b = (c = 13))

The rightmost assignment is done first, followed by the one to the left, and so on.

C provides other assignment operators, of which += is the most widely used. In Program P5.3,

above, we used the statement

sum = sum + num;

to add the value of num to sum. This can be written more neatly using += as:

sum += num; //add num to sum

n += 3

To add 3 to n, we could write

which is the same as

n = n + 3

Other assignment operators include -=, *=, /=, and %=. If op represents any of +, -, *, /, or %, then

variable op= expression

is equivalent to

variable = variable op expression

101

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!