Menu

Range-for loops and Raw for loops..

LW
2023-10-11
2023-10-11
  • LW

    LW - 2023-10-11

    Version (2.12) is run as cppcheck --enable=all xxx.cpp, on some contrived code (below) and it generates this warning:

    xxx.cpp:8:0: style: Consider using std::any_of algorithm instead of a raw loop. [useStlAlgorithm]
        if(strlen(animal) > 4)
    ^
    Active checkers: 161/565
    

    Contrived code:

    #include <stdexcept>
    #include <cstring>
    
    int main() {
      for (const auto & animal : {"cat", "bat", "tiger", "rat"})
        if(strlen(animal) > 4)
          throw std::runtime_error("Danger ahead");
      return 0;
    }
    

    Is it possible (maybe a future enhancement if not currently available) to please treat range-for loops, a feature of C++11, separate from the raw loops that have been part of C and C++98.

    Sean Parent (who has been quoted here in this discussion forum) didn't banish range-for loops, please note, when he actually showed those really bad examples of raw for-loops. He supports range-for loops: https://youtu.be/W2tWOdzgXHA?t=1750.

    Style-usage dogmas can generate unnecessary debate and animosity.. it is arguable if the above style warning is really useful here (still using c++17 compiler) .. in this sample contrived code above --and its usage of strlen() etc. are not the focus here, for there are many good real life examples, e.g. processing some selected input arguments to main() -- but please just listen to the video snippet above for a couple of minutes , to be assured that the criticism of raw for loops doesn't apply to range-for loops. Now of course, one can ill-code range-for loops too, but that is a different topic.

    I certainly won't begrudge raw for-loop haters their fair share of style warnings.. but .. I hope such style warnings can selectively be turned off for range-for loops by some config flag. Or maybe via some flag specifying c++17 vs c++98 .. whatever..

    To summarize: raw for-loops and range-for loops have a different anatomy, just observe its colon :-)
    Thank you.

     
  • CHR

    CHR - 2023-10-11

    Thanks for reporting, ticket is here: https://trac.cppcheck.net/ticket/12064

     
    👍
    1

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.