In C — or, for that matter, several other languages such as Python or C++ — most native types can be coerced to a boolean type: expressions that deliver integers, pointers or characters are automatically treated as boolean values whenever needed. For example: non-zero integer expression and non-NULL pointers evaluate to true whereas zero or NULL evaluate to false.

Many programmers take advantage of this fact by stating their conditionals like this:

void func(const int in) {
if (in) {
... do something when in != 0 ...
} else {
... do something else when in == 0 ...

... or even do something like:

bool func(const struct mystruct *ptr) {
int out = calculate_out(in);

... do something more with out ...

return out; // The return type is bool though; is this ok?

... but such idioms are sloppy and can introduce confusion or bugs. Yes, things work in many cases, but "work" is not a synonym for "good" ;-)

Taking advantage of coercions (automatic type conversions) typically makes the code harder to follow. In statically-typed languages, whenever you define a variable to be of a particular type, you should adhere to said type by all means so that no confusion is possible. Conceptually, an integer is not a boolean and therefore it should not be treated as such. But this is just a matter of style.

On the other hand, the automatic conversions can lead to hidden bugs; for example, in the second function above, did we really want to convert the "out" value to a boolean or was that a mistake?  This is not so much a matter of style but a matter of careful programming, and having as much state as possible "in your face" can help prevent these kind of trivial errors.

In contrast, one would argue that having to provide explicit checks or casts on every expression is a waste of time. But keep in mind that code is supposed to be written once and read many times. Anything you can do to communicate your intent to the reader will surely be appreciated.

Disclaimer: the above is my personal opinion only. Not following the style above should have no implications on the resulting binary code. (Wow, this post had been sitting as a draft around here for a too long time.)

Subscribe via RSS · Go to posts index

   Delivered by FeedBurner

Comments from the original Blogger-hosted post: