4 ms·
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 n
by russellbeattie 9y ago
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++)"
- dotancohen 9y agoWhich IDE so you use? Even VIM has plugins to warn on assignment in an if() statement.
- jandrese 9y agoDon't compilers warn about assignment inside of conditionals now?
- gumby 9y agoIn 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.
- gowld 9y agoThe compiler warns unless you add an extra () around the assignment to signal that you mean it.
- OskarS 9y agoIt'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)) { ... }
- ben509 9y agoSame here. I have flycheck running a linter, so I catch it a bit quicker, but single = is my single most common typo.
- lloeki 9y agoThere 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-in-condition https://github.com/bbatsov/ruby-style-guide#safe-assignment-...
- syrrim 9y agoYou can catch this in c using -Wall.
- invalidusernam3 9y agoThis is why I'm a big fan of yoda notation where applicable if (2 == x)
- palunon 9y agoOr simply enable compiler warnings for that...
- pandemi 9y agoUsing = for equality checking in SQL doesn't help with the occasional mistakes...