Commented short fancy code vs. uncommented longer easy-to-understand code – which is preferred

codingcomparisonprogramming practices

Sometimes an algorithm can be written in two ways:

  • The short, fancy way; or
  • The longer, easy-to-understand way.

For example, here is a longer, easier way of copying a string source to dest in C:

*dest = *source;
while (*source != '\0') {
    source++;
    dest++;
    *dest = *source;
} (true);

And here is a short, fancy way.

// Copy string source to dest
while (*dest++ = *source++);

I've always heard and read that fancy code should be avoided, and I tend to agree. But what if we take comments into account? Assume that, as in the examples above, we have an uncommented, longer and supposedly easier-to-understand code, and a well-commented, short, fancy code? Is the non-fancy code still preferred?

EDIT: Many have commented on variable names, so I've modified the example code as to not make that a factor when preferring on over the other. I tried to remove the double assignment in the first example, but that only made the code less readable.

Perhaps this wasn't the best of examples because many find the 'fancy' code more readable and understandable than the longer code. The idea was to have one longer code which was much easier to understand than a very short but complicated code.

EDIT2: Here's a new examle I got from SO:

Commented fancy version:

//direct formula for xoring all numbers from 1 to N
int Sum = (N & (N % 2 ? 0 : ~0) | ( ((N & 2)>>1) ^ (N & 1) ) );

Non-commented long version:

int Sum = 0;
for (int i = 1; i < N; ++i)
{
   Sum ^= i; //or Sum = Sum ^ i;
}

Best Answer

I would generally prefer to extract the fancy code out into its own method..

Rather than comment the fancy code, its method name should be all it needs to make things clear.

char *copy_string(char *s, const char *t) {    
    while (*s++ = *t++); 
    return s;
}