Hacker News new | ask | show | jobs
by dcvuob 3769 days ago
Those if statement should be written using the ternary operator. In my subjective opinion, putting the expression in the same line as the if statement is awful. Objectively it is worse because you create a possibility of certain types of errors, like a hanging statement or similar. Ternary operator doesn't have those.

The second example is missing error checking. So the real code isn't that nice.

My point is that C shouldn't look like Python. Small amount of functionality should be written unambiguously and take a lot of space if necessary. Because of the nature of C, it needs a lot boilerplate, and will take a lot of screen space anyway, but that is not a problem, as we are not coding on paper.

3 comments

It would be really nice if instead of downvoting, someone could provide a counterargument, or comment on parts the disagree.
I downvoted it to indicate that I don't agree with your preference. I rarely downvote for disagreement, but this was a case where I thought it worthwhile to offer the feedback that others strongly do not share your view. My equally strongly felt subjective personal belief is that single line if statements without braces are fine, but that once a second line is required braces should be mandatory.

I find the single line "if" statement without braces to be clearer and simpler than ternary with a (void) expression, and don't think the downsides are significant. It breaks if you were to add another statement after the semicolon on the same line, but I think that should almost always be avoided anyway.

I do find it interesting that others prefer two-line without braces over the single line approach. I find this one to be more dangerous than the single line. Possibly because with line-oriented debuggers it can be hard to set the right breakpoint?

It's quite possible that others are downvoting because they think you are trolling, and that no one would actually believe the ternary operator to be clearer. I wondered also about your defense of Allman braces, which I didn't downvote because I think it's a good example of how different the others's views can be on what seems obvious. While I think (some of) your views are in the (very small) minority, please keep posting them!

How would you use the ternary operator there? Like this?

    image ? foo_release(image) : 0;
Yes. And cast that 0 to (void), so the compiler won't complain over an unused expression.

Any C programmer will recognize what (void)0 means, do nothing.

Sure, but I find it strange to use the ternary operator and discarding the value. It's not wrong, but I think most C programmers prefer a simple if statement.
I was giving an replacement for the if statement presented above, where both expressions are on the same line.
I'm closing in on year 25 of programming in c, and I still refuse to use the ternary operator.