#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2010
    Posts
    68
    Rep Power
    4

    Do Lambdas Hurt Readability?


    Do lambdas (especial nested lambdas) hurt readability C++? I realize that the program will run just the same with or without them, but I'm having a harder time analyzing lambdas when compared to typical loops.

    I don't mind single lambdas, but once they become nested, the readability of the code seems to diminish for me. Should I just keep using lambdas and avoid loops when a stl algorithm will suffice, or would rolling my own loops be better when I think lambdas hurt readability?

    I'm assuming it's only a matter of time until lambdas start feeling as natural as loops, but I was wondering if anyone else had advice on this.

    Here's an example.
    (Probably a bad example since there's no distinct advantage to using stl algorithms in this case)

    Code:
    std::vector<int> calculateSums(const std::vector<std::vector<int>>& arg) {
         std::vector<int> sums;
         std::for_each(arg.begin(), arg.end(),
             [&] (const std::vector<int>& vec) {
                 int sum = 0;
                 std::for_each(vec.begin(), vec.end(),
                     [&] (int value) {
                         sum += value;
                     }
                 );
                 sums.push_back(sum);
             }
         );
         return sums;
    }
    vs
    Code:
    std::vector<int> calculateSums(const std::vector<std::vector<int>>& arg) {
         std::vector<int> sums;
         for (auto vec: arg) {
             int sum = 0;
             for (auto i: vec) {
                 sum += i;
             }
             sums.push_back(sum);
         }
         return sums;
    }
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    185
    Rep Power
    82
    It seems as though the defacto guidelines suggest that a lambda should contain exactly one semicolon, two in rare cases. If you need more then it is probably not a good candidate for a lambda from a readability viewpoint and using a method or function would be a better alternative for readability.

IMN logo majestic logo threadwatch logo seochat tools logo