code_junkie

What is the purpose of anonymous { } blocks in C style languages

Nov 14th, 2011
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.08 KB | None | 0 0
  1. void function()
  2. {
  3.  
  4. {
  5. int i = 0;
  6. i = i + 1;
  7. }
  8.  
  9. {
  10. int k = 0;
  11. k = k + 1;
  12. }
  13.  
  14. }
  15.  
  16. void function()
  17. {
  18. {
  19. std::ofstream out( "file.txt" );
  20. out << "some datan";
  21. }
  22. // You can be sure that "out" is closed here
  23. }
  24.  
  25. void function() {
  26. // ...
  27. {
  28. // lock some mutex.
  29. mutex_locker lock(m_mutex);
  30. // ...
  31. }
  32. // ...
  33. }
  34.  
  35. void function() {
  36. // set up timer A
  37. {
  38. int config = get_config(TIMER_A);
  39. // ...
  40. }
  41.  
  42. // set up timer B
  43. {
  44. int config = get_config(TIMER_B);
  45. // ...
  46. }
  47. }
  48.  
  49. glPushMatrix();
  50. {
  51. glTranslate(...);
  52. glPushMatrix();
  53. {
  54. glRotate(...);
  55. // draw some stuff
  56. }
  57. glPopMatrix();
  58. // maybe draw some more stuff
  59. }
  60. glPopMatrix();
  61.  
  62. switch (i)
  63. {
  64. case 0 :
  65. int j = 0; // error!
  66. break;
  67.  
  68. switch (i)
  69. {
  70. case 0 :
  71. {
  72. int j = 0; // ok!
  73. }
  74. break;
  75.  
  76. class ExpensiveObject {
  77. public:
  78. ExpensiveObject() {
  79. // acquire a resource
  80. }
  81. ~ExpensiveObject() {
  82. // release the resource
  83. }
  84. }
  85.  
  86. int main() {
  87. // some initial processing
  88. {
  89. ExpensiveObject obj;
  90. // do some expensive stuff with the obj
  91. } // don't worry, the variable's scope ended, so the destructor was called, and the resources were released
  92. // some final processing
  93. }
  94.  
  95. {
  96. int[] myArray = new int[1000];
  97. ... // Do some work
  98. }
  99. // The garbage collector can now reclaim the memory used by myArray
  100.  
  101. int a=25;
  102. int b=30;
  103. { //at this point, a=25, b=30
  104. a*=2; //a=50, b=30
  105. b /= 2; //a=50,b=15
  106. int a = b*b; //a=225,b=15 <--- this new a it's
  107. // declared on the inner scope
  108. }
  109. //a = 50, b = 15
  110.  
  111. int main() {
  112. /* Blah blah blah. */
  113. {
  114. int i;
  115. for (i = 0; i < 10; ++i) {
  116. }
  117. }
  118. }
  119.  
  120. int MyClass::foo()
  121. {
  122. // stuff uncritical for multithreading
  123. ...
  124. {
  125. someKindOfScopeLock lock(&mutexForThisCriticalResource);
  126. // stuff critical for multithreading!
  127. }
  128. // stuff uncritical for multithreading
  129. ...
  130. }
Add Comment
Please, Sign In to add comment