Hacker News new | past | comments | ask | show | jobs | submit login

It's been my impression over the years that = vs. == is one of the most common mistakes made in languages that use them. In which case, can it really be said to be less confusing?



There are two orthogonal issues here:

1) Do you allow assignment as an expression?

2) Do you use the same operator?

If you answer "yes" to #1, you must answer no to #2, but if you answer no to #1 you can choose whether or not you use the same operator. Consider these examples (assuming that if they're different, we use =/==, but of course any other set of operators could be substituted):

    # A) if 'yes' to 1 this would be a "double assignment", setting both a and b to c.
    a = b = c

    # B) if 'no' to 1, and 'yes' to 2, this would be an assignment of the comparison of b and c to a:
    a = b = c

    # C) if 'no' to 1 and 'no' to 2, this would be an assignment of the comparison of b and c to a:
    a = b == c

    # D) if 'no' to 1 and 'no' to 2, this would most likely be a syntax error:
    a = b = c
With respect to confusion, I'd argue that B) creates a lot of potential for confusion. You'd want "a = b = c" to either be "double assignment" (A) or a syntax error (D). If your language does not allow assignments as expressions, I'd go for C/D exactly for the reason you give, as the main reason not to allow assignments as expressions tends to be exactly to avoid the mistake you mention (it's trivial to support in a compiler/interpreter, so it's a question of whether you believe it's more helpful or more damaging)


Modern languages using that syntax tend to prevent that mistake by either outright disallowing assignments in boolean contexts, or by not having implicit conversion of other types to boolean, meaning that the mistake would be limited to the case of comparing a boolean variable to another value, which is quite rare. Some languages further limit the risk by making variables unmodifiable by default, meaning that it would have to be an explicitly modifiable boolean variable.

Assignment is one of the most frequent operations in typical programming languages, so it makes sense for it to be a single-character symbol, and ‘=’ is about the only fitting ASCII symbol for that. (With non-ASCII, there would be ‘≔’ or ‘←’ (the latter being used by APL), but those are non-obvious to type.)




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: