[cs13001] on increment and decrement

Mikhail Nesterenko mikhail at cs.kent.edu
Mon Feb 4 12:46:11 EST 2013


CSI students,

There was a discussion on increment and decrement operations in one of
the classes. Several clarifications.

* Increment and decrement operations can only apply to a variable. The
  precise term for it is "l-value": something that has an explicit
  address in memory (whose value can be decremented or incremented).

  Expressions are not l-values. Therefore, operations like this:

	a =(b+5)++; 

  are not allowed. Microsoft's compiler generates error:

        '++' needs l-value

  Moreover, 
	a = (b++)++;

  is also not allowed (the increment in parentheses is considered an
  expression).

  However, this expression is perfectly legal:

	a = b++ + ++c;   // "b" and "c" are incremented, their values are
	  	         // summed and assigned to "a"
			 // note old c's value is used in the expression	
   
* In modern programming, the suffix form of the increment/decrement is
  considered inefficient and is to be avoided. The reason is
  this. Consider the statement below

      a = b++ - 33 + (a*c-33);

  Variable "b" is incremented using the suffix form. This means that
  the old value of "b" is used in the expression. When compiler
  generates object code, it has to create a temporary variable to
  store the old value (either to be used in the expression or to be
  assigned to the variable). This inefficiency may be minor for
  the types with have studied so far. However, it may be significant
  for the classes/objects that we will study later.

  Note that there is no need for temporary variables, and no resultant
  inefficiency in case the prefix from of the increment is used:

      a = ++b - 33 + (a*c-33);


Thanks,
-- 
Mikhail


More information about the cs13001 mailing list