Technical

Forgotten C: The comma operator

Comma operator?! Isn’t that thing just a separator? Nope. It’s occasionally an operator. And it can do this:

int i = (0, 1, 2, 3, 4, 5);

Know what that does? It evaluates the constants 0 through 4, discards the results, and then evaluates and returns the constant 5, which is assigned to ‘i’. Why is that useful? It’s not. The evaluation of the constants is probably optimized away by most compilers. But, the comma introduces a sequence point, so you can do disgusting things like this, ensuring the order of evaluation:

int i = (a2d_init(), a2d_fetchvalue());

I don’t care how expressive you are—don’t ever do that. Just know that you CAN do it and that doing it makes you a bad person. Other, more kosher, but still questionable uses include loops:

for (i = 0, j = 256; i < 256; i++, j--) { … }

That is all. I had personally completely forgotten about this infrequently-used operator until I encountered some strange code recently:

#include <stdio.h>
struct S0 {
  unsigned f1 : 1;
};

struct S0 s;

int main (void) {
  int x = -3;
  int y = x >= (0, s.f1); /* Ooh! Here it is! */
  printf ("%dn", y);
  return 0;
}

It’s a reduced test case for compilers, so no—it’s not supposed to make any sense to you. If you’re curious though, you can read more about it here.


Well, hello there HN, reddit, and DZone. I didn’t realize language pedantry was so universally piquing. If you’re interested in embedded development and crave diversity, note that we’re hiring for positions in San Francisco.