Assignments Are Expressions

AssignmentsAreExpressions is probably defined somewhere else on this wiki, please tell me where. Anyway, they are the property of the assignment (x = y) or (x := y) returning a value.

CeeLanguage has AssignmentsAreExpressions; z = (x = y) * 2 is OK in C.

AssignmentsAreExpressions are sometimes ConsideredHarmful, because of the common noob mistake made with them:

 if (x = 1) {
/* always do this */
 } else {
/* never do this */
 }
... even though they intended
  if (x == 1)
Experienced C* developers often learn to favor:
  if(1 == x)
based on the notion that the compiler will catch it for them if they make a typographical error:
  if(1 = x)
[Just by the way, "experienced" C* developers don't create this problem for themselves in the first place.]


GoLanguage splits the difference admirably.

 x := 1  #  initialize new var x
 x = 2  #  stick 2 into preexisting var x
 3 == x  #  returns false
Question - is if x := 1 valid in Go?


Java also has this to an extent, though the entire expression within a conditional needs to ultimately return a boolean. The expression

 while((c = System.in.read()) != -1)
     /* Do something if not at end of input. */
will work.


CategoryCodingIssues


EditText of this page (last edited April 2, 2011) or FindPage with title or text search