开发者

Need a short, complicated C++ code and a longer, understandable version

开发者 https://www.devze.com 2023-01-20 09:31 出处:网络
In this question, I tried to give an example of two ways of doing the same thing in C++: one short but complicated \"fancy\" piece of code; and a longer but more readable and understandable way of doi

In this question, I tried to give an example of two ways of doing the same thing in C++: one short but complicated "fancy" piece of code; and a longer but more readable and understandable way of doing the same thing. The question asks whether it's better to have a well-commented fancy piece of code or a self-commented (i.e. no comments) longer version.

The problem with my example was that the fancy version turned out to be more understandable than the non-fancy version. Since I can't think of any good examples, I figure I'd try asking here. So what I need is two examples of C++ code which produce the exact same result, but in one version the code is short but very complicated and cannot be understood immediately without having to think about it, and a longer but much more readable and understandable version.

I want someone to look at the fancy version and go "Shit, that's com开发者_如何学Pythonplicated. I'm glad it's commented, otherwise I wouldn't have understood what it does" and then look at the longer version and go "Ah, I understand what it does, even without comments". The shorter example should be something like 1-10 lines and the longer maybe 10-30 lines.


How about this?

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

instead of:

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

Formula taken from here


Do you mean something along these lines?

First version:

int srtcpy(char *dst, char const *src) {
    char *dst_start = dst;
    while (*dst++ = *src++); // Incrementally copy *src to *dst until *src is 0
    return dst_start;
}

Second version:

int srtcpy(char *dst, char const *src) {
    char *dst_start = dst;
    while (*src != '\0') {
        *dst = *src;
        dst = dst + 1;
        src = src + 1;
    }
    *dst = '\0';
    return dst_start;
}

The more interesting question now is: What about the compiled versions of these functions: do they differ once compiled and optimized? Is the first actually faster than the second? What is the actual gain of writing fancy pieces of code?

0

精彩评论

暂无评论...
验证码 换一张
取 消