0

while reading many codes i have seen that the editor implements {} in the main() function or other functions other than mandatory ones. i will give an example:

int main(){
   int num1, num2;
   float num3;
   {
      std::cout << "Uploading ..." << std::endl;
      num3=0.3;
   }
   num1 = 2;
   num2=num1+2;
}

my question is what is the purpose of implementing { bla; bla; bla; } in the function? i mean this part:

       {
      std::cout << "Uploading ..." << std::endl;
      num3=0.3;
       }
eng86
  • 1
  • 4
    `{}` is used to define a new [scope](https://en.cppreference.com/w/cpp/language/scope). But, in this particular example, defining a new *block scope* around code that does not declare any local variables within that scope is pretty pointless, the scope will just be ignored or optimized away. – Remy Lebeau Mar 19 '20 at 23:41
  • 2
    Q: What's the purpose of `{}` in this example? A: It creates a new [scope](https://www.geeksforgeeks.org/scope-rules-in-c/). I'm more familiar with the construct `{ float num3 = 0.3; std::cout << num3 << std::endl; }`, in which case "num3" would be an [automatic variable](https://en.wikipedia.org/wiki/Automatic_variable) whose lifetime would exist only inside the braces. – FoggyDay Mar 19 '20 at 23:45
  • 2
    Does this answer your question? [Can I use blocks to manage memory consumtion in C++?](https://stackoverflow.com/questions/581097/can-i-use-blocks-to-manage-memory-consumtion-in-c) – rsjaffe Mar 19 '20 at 23:45

0 Answers0