Menu

Bad recommendation to "reduce" scope

mcandre
2018-04-18
2018-04-19
  • mcandre

    mcandre - 2018-04-18

    cppcheck often recommends that variables be moved deeper into code blocks such as FOR and WHILE loops. This is actually bad form, as the declaration becomes much more expensive to perform inside the loop than before the loop. Recommending that variables be moved inside IF / ELSE / ELSE IF blocks is helpful for C99+ code, but doing the same for FOR / WHILE blocks encourages poor performance.

     
  • versat

    versat - 2018-04-19

    I have searched and read a bit and i am somewhat with you. There could be cases in which it can cost performance when a variable is declared inside a loop. That is particularly true for C++ when a class with a heavy constructor is instantiated again and again inside a loop.
    But i also read some comments about positive effects (also wrt. performance) when variables are declared inside a loop.
    And as it is often hard to say what the compiler exactly does/optimizes there is not the one and only solution. When it comes to performance it is normally necessary to profile the program and use this information to optimize it.
    If you have some good sources about that topic could you share them?
    Maybe it is enough to extend the message from Cppcheck to warn that it could cost performance when a (complex) variable is declared inside a loop?
    Or maybe it makes sense to mark the message as inconclusive when the scope of the variable will be inside a loop?
    Any other suggestions?

     

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.