Hacker News new | ask | show | jobs
by mikevm 4654 days ago
Makes one appreciate languages like Pascal which differentiate between the equality operator '=' and the assignment operator ':='.

I wonder why the decision was made in C to use '=' and '=='? I'm betting it has something to do with the laziness of the programmers :).

1 comments

The problem is not in == vs =, it's in allowing assignment as an expression. Go fixes this, for example, by now allowing them: if a = 0 {} gives compile error.
The problem is that == and = look similar. Banning assignment as expression only makes the language less expressive. Common Lisp fixes this, by having assignment and comparison look completely different: (setf variable value) vs (eql variable value)
Bit of a bummer, I often find using assignment as an expression useful, like if (x = y as String) == null or such in c#. I get the feeling Go sacrifices a bit too much freedom.
I'm not a professional programmer by any stretch, but wouldn't this problem completely go away if the C and C++ compilers detect a single = inside an if statement and outright refuse it. Either that or automatically substitute the assignment with checking for instances inside the if-condition.

The reason I'm asking is, because I don't know if there's ever a case where you'd want to assign right inside the if-condition. Is there?

There can be:

    if (Foo *foo = getFoo()) { // getFoo returns null if there is no foo
        // There is a foo
    }
However, this problem is basically entirely addressed by compiler warnings, which generally ask you to add an extra set of parens for this case.
Or you could also blame it on not having branch statements which enforce the use of a boolean type.

Edit: Actually, forget I said this. It's a dumb statement. 'if(a = true)' would always pass, regardless of the value of 'a'.