S
S
sddvxd2018-12-03 12:56:18
C++ / C#
sddvxd, 2018-12-03 12:56:18

"Unreadable" code?

Good afternoon! I'm doing an assignment in a tutorial, it says to write a function to "reverse" a string. I remembered the convenient for statement, how can I abuse it, and how understandable is this code?

char* rev(const char* str){
    int length = 0;
    const char* pchar = str;
    for(; *pchar; ++length, ++pchar);
    char* new_char = new char[length + 1];
    for(char* pnew_char = new_char; *pnew_char++ = *--pchar;); //pchar == '\0', поэтому префиксный --
    return new_char;
}

int main(int argc, char *argv[])
{
    cout << rev("hello") << '\n';
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vasily Melnikov, 2018-12-03
@sddvxd

Well, let's start with the fact that the string can be reversed without allocating additional memory. Secondly, it is not worth returning a pointer to the allocated memory block from the function without unnecessary necessity. Otherwise, at least it will be necessary to make a function for freeing this block.
As for cycles. You can do this if it doesn’t bother anyone in the team, but in my opinion it’s not necessary. It's just that modern compilers perfectly optimize the code, and there is no practical need for such exercises, and it is much easier to make a mistake. It is not for nothing that cycles by ranges and other goodies have been added to the new standards.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question