Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reasons for putting C/C++ variables in an unnamed scope? [duplicate]

Possible Duplicate:
Can I use blocks to manage scope of variables in C++?

I came across some C++ code that resembled:

int main(void) {

  int foo;
  float qux;
  /* do some stuff */

  {
    int bar;
    bar = foo * foo;
    qux = some_func(bar);
  }

  /* continue doing some more stuff */
}

Initially I thought that perhaps the original author was using braces to group some related variables, but being that the system under design doesn't have an abundance of memory I thought the author might have had the intention of having bar's scope resolve and any variables with in go away rather than have them around for the entire enclosing (foo's) scope.

Is there any reason to do this? It seems to me this shouldn't be necessary and that any modern compiler makes this unnecessary?

like image 406
John Carter Avatar asked Nov 03 '12 03:11

John Carter


2 Answers

It seems to me this shouldn't be necessary and that any modern compiler makes this unnecessary?

Yes, modern compilers will optimize the memory usage in cases like this. The extra scope won't make the code faster or more memory efficient.

However, they can't optimize objects with destructors with side-effects as that would change the behavior of the program. Thus, this makes sense to do for such objects.

Is there any reason to do this?

It is useful to group related code together. You know that variables declared inside the braces won't be used anywhere else which is extremely helpful to know.

like image 129
Pubby Avatar answered Oct 20 '22 18:10

Pubby


If you do that multiple times in a single method, that could result in that method taking up less stack space, depending on your compiler. If you're resource limited, you might be on a microcontroller, and their compilers aren't always as full-featured as x86 compilers.

Also, if you do that with full classes (instead of ints & floats), it lets you control where the destructor is called.

class MyClass;

int main(void) {

    int foo;
    float qux;
    /* do some stuff */

    {
        MyClass bar;
        qux = some_func(bar);
    } // <-- ~MyClass() called here.

    /* continue doing some more stuff */
}
like image 37
David Yaw Avatar answered Oct 20 '22 18:10

David Yaw