Re:Why Does “=” Mean Assignment?
by russellbeattie on Tuesday April 10, 2018 @04:22PM
(#16804945)
I've been programming professionally for 25 years using mostly C inspired languages, and I will still regularly write "if(foo = bar)" on a daily basis and not notice until there's an error. It's easily the most common syntax error I write, followed closely by using commas in my for-loop as apparently it looks like a function to my fingers: "for(x=0, x<10, x++)"
[ Parent
| on HN ]
There is a Ruby idiom[0] that I find quite useful (esp. combined with a linter such as Rubocop), leveraging optional parens as a marker of intentional assignment:
# bad
if v = array.grep(/foo/)
do_something(v)
# some code
end
# good
if (v = array.grep(/foo/))
do_something(v)
# some code
end
Caught a number of nasty bugs that way.[0]: https://github.com/bbatsov/ruby-style-guide#safe-assignment-...
You can catch this in c using -Wall.
Re:Why Does “=” Mean Assignment?
by invalidusernam3 on Tuesday April 10, 2018 @08:05PM
(#16806888)
This is why I'm a big fan of yoda notation where applicable
if (2 == x)
Or simply enable compiler warnings for that...
Don't compilers warn about assignment inside of conditionals now?
In C++17 not only can you do assignment in the conditional, you can declare new variables which have the scope of the then and else clauses.
But yes, most compilers will catch this case.
The compiler warns unless you add an extra () around the assignment to signal that you mean it.
It's used often enough in loops like this:
while (v = next()) { ... }
or, perhaps more usefully: while ((v = next()) != ERROR) { ... }
EDIT: just did a quick check, and LLVM did in fact warn me about this: if (x = 4) { ... }
To silence the error, you have to double up on the parenthesis, which I guess is a reasonable enough solution: if ((x = 4)) { ... }Same here. I have flycheck running a linter, so I catch it a bit quicker, but single = is my single most common typo.
Re:Why Does “=” Mean Assignment?
by dotancohen on Tuesday April 10, 2018 @04:51PM
(#16805249)
Which IDE so you use? Even VIM has plugins to warn on assignment in an if() statement.