SUNET icon indicating copy to clipboard operation
SUNET copied to clipboard

deduce variable type

Open paulpach opened this issue 7 years ago • 0 comments

In C++11, it is recommended to deduce the type when possible by using auto, in some instances it is faster because it avoids type conversion, and it is easier to read when you declare several variables. For a longer explanation watch this video:

https://www.youtube.com/watch?v=xnqTKD8uD64&t=2474s starting at minute 29

for example, this code:

    int n = strlen(http_str.c_str());
    int tot_len = n;
    while (n > 0) {
        int nwrite = send(_clt_sock_fd, http_str.c_str() + tot_len - n, n, 0);
        if (nwrite < n) {
            break;
        }
        n -= nwrite;
    }

could be done like this:

    auto n = strlen(http_str.c_str());
    auto tot_len = n;
    while (n > 0) {
        auto nwrite = send(_clt_sock_fd, http_str.c_str() + tot_len - n, n, 0);
        if (nwrite < n) {
            break;
        }
        n -= nwrite;
    }

In some cases auto is faster because it guarantees no type conversion.

paulpach avatar Jun 15 '17 12:06 paulpach