C++ Programming Practices – Is Creating Blocks of Code Bad Practice?

ccoding-standardscoding-styleprogramming practices

In C++, is it bad practice create blocks of code inside some function, such as the following:

    bool f()
    {
       {
           double test = 0;
    
           test = // some other variable outside this function, for example.
    
           if (test == // some value)
             return true;
       }
    
       {
           double test = 0;
    
           test = // some variable outside this function, different from the last one.
    
           if (test == // some value)
             return true;
       }

       return false;
    
    }

The point of doing this would be to use the same variable name of "test" multiple times, for the same type of procedure. In my actual project, I have multiple variables and am performing multiple tests. I don't really want to keep creating new variables with different names for each of the tests, considering how the tests are so similar.

Is it bad practice to insert blocks of code so that the variables go out of scope after each test, and then I can use their names again? Or should I seek another solution? It should be noted that I considered using the same set of variables for all my tests (and just setting them all to 0 after each test was over), but I was under the impression this may be bad practice.

Best Answer

Blocks are perfectly reasonable if you're using them to scope some resource. Files, network connections, memory allocations, database transactions, whatever. In those cases, the block is actually part of the logical structure of the code: you spawn a resource, it exists for some period of time, and then it goes away at a designated time.

But if all you're doing is scoping a name, then I would say that they are bad practice. Generally speaking, of course; special circumstances can apply.

For example, if this function were generated by some code generation system, testing framework, or the like, then blocks for the sake of name scoping is a reasonable thing. But you'd be talking about code written for the purpose of a machine, not a human.

If a human is writing code where they need to reuse names within the same function, I would say that those blocks probably need to be separate functions. Especially if those names are being used with different types and/or meaning within those blocks.