Search code examples
conditional-statementslanguage-agnosticvariable-assignment

Why would you use an assignment in a condition?


In many languages, assignments are legal in conditions. I never understood the reason behind this. Why would you write:

if (var1 = var2) {
  ...
}

instead of:

var1 = var2;
if (var1) {
  ...
}

?


Solution

  • It's more useful for loops than if statements.

    while(var = GetNext())
    {
      ...do something with 'var' 
    }
    

    Which would otherwise have to be written

    var = GetNext();
    while(var)
    {
      ...do something
      var = GetNext();
    }