For no particular reason I decided to write the following confusing line of C code today…

const _=0;do;while(0?0,1:!_,_);

Might make an interesting interview question. Can you parse it in your head?

Here are some reasons why this seems very confusing:

  1. const _=0;This is not much different than “const int a = 0;”… It is just using the implied “int” type, and rudely using the single underscore character, which is acceptable (but taboo) as a variable name.
  2. do;whileThis looks odd, but is actually valid. Typically, people implement a do/while as “do{}while(…);” – however, it is equally valid to replace the {}’s with a single statement, even an empty do-nothing statement (“;”).
  3. a?b:cI am tempted to fail somebody in an interview immediately if they have no clue what this operator does. It isn’t that it’s particularly critical or anything -but if you’re a C coder and you’ve been around the block – it would be very odd for you to not be familiar with the conditional operator. Still, it is rare enough to be difficult to brain-parse.All this does is evaluate “a”, and if the result is true, evaluates “b”. If the result if false, it evaluates “c”. Simple.
  4. !_,_ Okay so this one is nasty. I might not expect everybody to be familiar with this guy. What happens here is the variable “_” is being evaluated as negated, then the variable “_” itself is being evaluated. The trick is, only the right side of the comma is actually used as the value of the expression. Huh?

    This is primarily useful in things like a “for” loop. Since the general syntax of a for loop is “for(a;b;c)”, you at first may feel a little limited. How can I increment two variables on each step? Easy. “for(a;b;d++,e++)” – note the comma operator allows you to squeeze two subexpressions into “c”. In this case, nobody knows or cares that the expression value is, in the end, defined only by e++. The result is not being used at all.

    I’d be interested to hear some real world valueable uses for the comma operator, aside from a “for” loop.

2 thoughts on “Ridiculous C-code

  1. The other use (obvious, of course), is int a,b,c=6; and so on.

    Also, a way of making this code even more confusing would be something like

    __(int ___,…)
    const _=0;do;while(0?0,1:!_,_);

    You’re not using the parameter(s), but the objective of this isn’t to write functional code anyway 😀



  2. took me a minute to realize the meaning of that. might as well reuse _ as the function name, too.

    _(int __,…) { const _=0;do;while(0?0,1:!_,_); }

    now that is some ugly code


Leave a Reply

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

You are commenting using your 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 )

Connecting to %s