C obscenities – three increment operators

One of the peculiarities of C is that it provides three (or actually four) methods of incrementing  a variable by 1.

a = a + 1;
a++;
++a;
a += 1;

The confusion often lies as to why this is necessary. In the early 1970s when computing was still in its infancy, machines had few resources, and languages were designed to create efficient code. Although conceptually all these statements look the same, at the processor level, they all work differently. The term a+=1 may be interpreted as:

  1. Find the memory location identified by a
  2. Add 1 to the value

However the expression a=a+1 is more complicated:

  1. Evaluate a+1
    • Find the memory location identified by a
    • Copy the value stored in a into a temporary location
    • Add 1 to the value in the temporary location
  2. Store the result in a
    • Find the memory location identified by a
    • Copy the value in the temporary variable to it.

Yet four ways of incrementing a variable by 1 probably aren’t justified in a language – they just present confusion. If you can type a=a+1, you have a means of adding one to a variable – DONE!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s