dimanche 16 août 2020

Why is this allowed in If statements in various languages?

In various programming and scripting languages if statements use the following:

if ( var1 == 1) { do something }

As far as I know, every language that follows this convention also allows:

if ( var1 = 1) { do something }

This is a not too uncommon mistake even a seasoned programmer can make. Rather than a comparison, it is an assignment, which will (almost) always be successful and return a non-zero number, meaning true. The only time I think this would fail is if the variable isnt in scope or possibly a type mismatch. Yes, all its looking for a non-zero number, but is there a reason a comparison isnt required? Why is this allowed? Am I missing something obvious?

Aucun commentaire:

Enregistrer un commentaire