3 ms·
Doesn't `if` always require parenthesizes?
by sedeki 11y ago
Doesn't `if` always require parenthesizes?
- elisee 11y agoYes, in C, but I believe Udo was talking about other languages (like Go for instance) > and I also do if() even in cases where the language doesn't require it This sentence could be parsed in multiple ways though :)
- zoul 11y agoNot in all languages. For example, Go and Swift don’t require it.
- Udo 11y agoNo, not always. Not in Go, or in Rust, or Ruby, for example. The assumption being in these languages that if is followed by an expression and that expression is parsed to its natural end anyway - but this only works if the syntax allows for that end to be found without ambiguity.
- krylon 11y agoIn Go, however, go fmt will remove the unnecessary parentheses. I was very annoyed at first, when I saw this, but I got used to it.
- mcguire 11y agoDoes it generally do this in expressions, based on operator precedence, or is it limited to the outer parentheses on selected statements?
- krylon 11y agoI am not an expert, but I think it only removes the outermost ones. The major task of the tools is indentation and placement of curly braces.
- nikai 11y agoNot even in C. You can have an if condition that is actually a macro that expands with parentheses. For example the macros in ctype.h, so you can actually write if islower(c) { (..) }
- raverbashing 11y agoYeah, but macros are not really part of the language, they're more a writing aid than anything really. So, for the sake of good practices, write if with parenthesis.
- olavk 11y agoThat is cheating!
- cygx 11y agoThat's not portable, though: A comforming implementation may very well implement islower as a function call, and you should treat is as such.