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.

Chapter 5 ■ Programs with Repetition Logic

The moral of the story is that, whenever possible, you should try to anticipate the ways in

which your program might fail and cater to them. This is an example of what is called defensive

programming.

5.4 Increment and Decrement Operators

There are a number of operators that originated with C and give C its unique flavor. The best

known of these is the increment operator, ++. In the last program, we used

n = n + 1;

to add 1 to n. The statement

n++;

does the same thing. The operator ++ adds 1 to its argument, which must be a variable. It can be

written as a prefix (++n) or as a suffix (n++).

Even though ++n and n++ both add 1 to n, in certain situations, the side effect of ++n is different

from n++. This is so because ++n increments n before using its value, whereas n++ increments n

after using its value. As an example, suppose n has the value 7. The statement

a = ++n;

first increments n and then assigns the value (8) to a. But the statement

a = n++;

first assigns the value 7 to a and then increments n to 8. In both cases, though, the end result is that

n is assigned the value 8.

As an exercise, what is printed by the following?

n = 5;

printf("Suffix: %d\n", n++);

printf("Prefix: %d\n", ++n);

The decrement operator -- is similar to ++ except that it subtracts 1 from its variable

argument. For example, --n and n-- are both equivalent to

n = n - 1;

As explained above, --n subtracts 1 and then uses the value of n; n-- uses the value of n and

then subtracts 1 from it. It would be useful to do the above exercise with ++ replaced by --.

100

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!