-2

I have the following type of function. I am confused on what kind of declaration is that? I am only used to traditional type (may be called something else) where I have one block of codes after declaration of function. But here are two. Can you tell me what will this do?

static void afunction(atype *atype)
{
  {

         //Do stuff

  }

  {
         //Do stuff
    }
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
jkhadka
  • 2,443
  • 8
  • 34
  • 56

1 Answers1

4

All variables declared inside those blocks will be seen as local to that block, and their destructors (if any) will be called when leaving that block.

This can be used to 'hide' variables, or to call constructor/destructor in that block.

For example, for timing the execution of one block, you could initialize a variable of a class where the constructor sets a starting time, and the destructor gets the end time and caculates the duration.

This could also be used in the same manner for locking. At the end of the block, the lock is guaranteed to be released (destructor will be called), no matter how and where you exit that block.

Danny_ds
  • 11,201
  • 1
  • 24
  • 46