Your friend, the comma operator

C has had a comma operator for decades, the primary use of which is to separate function arguments.

By definition, the value of a comma separated statement is the right hand argument:

int i = j = 3, k = 4, l = 5;

sets i to 5, and is evaluated left to right. However, this is not the usage I have found for it.

Rather, I use it to bind statements that I fear some junior engineer is going to separate in the future – by mistake.

For instance:

[timer invalidate];
 timer = nil;

I could of course do:

{
    [timer invalidate];
     timer = nil;
}

but that looks like so much work for such a small thing. So instead, what I do is this:

[timer invalidate], timer = nil;

Its inconceivable that some developer in the future will separate those statements.

Thus, you can use the comma to tightly bind two or more statements together in a way that won’t get broken up by mistake.

Advertisements

2 thoughts on “Your friend, the comma operator

  1. I couldn’t disagree more! I used to use the comma operator in the same manner there are two things I find wrong with this usage: 1) It’s (very) non-standard and so may be thought to be an error and 2) it’s still not obvious why the statements are linked this way ie it does nothing to connect the two statements as part of some process. I would place the two statements in a separate method named “killTimer” or something like that, then we know that to kill a time you must invalidate the timer and set it to nil.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s