Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do c++ blocks { } have a negative impact

Tags:

c++

I have recently discovered that {} blocks can be used on their own. To me, this can be really aid readability in some cases For example, in the following code:

push();
foo();
push();
foo();
foo();
pop();
pop();

Can become (without fighting IDE auto indentation):

push();
{
    foo();
    push();
    {
        foo();
        foo();
    }
    pop();
}
pop();

Aside from subjective opinion over style, does this have any negative impacts (like less optimsation from the compiler, they have another use, etc) or are these blocks safe to use.

like image 665
Ross Avatar asked Oct 13 '13 20:10

Ross


3 Answers

When they don't change the meaning of the code (as in your example), there's no reason that they should have any effect on optimization. If they do, then it's a quirk of a particular compiler.

To enforce that your pop() calls map your push() calls you could even do this:

struct Pusher {
    Pusher() { push(); }
    ~Pusher() { pop(); }
};

...

{
    Pusher p1;
    foo();
    {
        Pusher p2;
        foo();
        foo();
    }
}

The pattern is generally called RAII. It does change the meaning of the code, though -- in my code pop() will be called if one of the calls to foo() throws an exception, in yours it won't. In most (but not all) situations where you need to undo something before returning, you also need to undo on an exception.

like image 90
Steve Jessop Avatar answered Nov 20 '22 02:11

Steve Jessop


Everything about your second example is 100% fine. The extra blocks might affect the scope of variables declared within them, but you aren't doing any of that.

like image 31
Carl Norum Avatar answered Nov 20 '22 01:11

Carl Norum


Creating blocks like this creates new scopes. Thus you'll have constructors and destructors running upon entry and exit to these scopes. You'll also have more chances for names to hide each other. They are safe to use but you have to keep these things in mind.

BTW, this is subjective, but I don't find your usage of scopes an aid to readability. You could have accomplished the same thing with blank lines. If I saw your code in a review I would ask myself why you were creating scopes like that.

One thing scopes are useful for are controlling lifetimes in conjunction with RAII style programming. In this example a scope is used to limit the amount of time a mutex is held.

int a = b + c;
{
   OS::Mutex::Lock lock(mutex);
   some_shared_variable = a;
}

Here Lock is an RAII style class that acquires a mutex in the constructor and releases it in the destructor. By explicitly using a scope you can limit how long the lock is being held.

like image 42
Brian Neal Avatar answered Nov 20 '22 03:11

Brian Neal