Is there any case in which putting code within brackets to reduce its scope is something that I might want to do, or is this one of those cases in which you guys will tell me, "If you need to do that in your code, then your code is badly written."
For example:
//***CODE**** { int foo=stuff; //use foo, and then I'm done using it forever } //****MORE CODE****
From what I've gathered the round brackets are used to contain the conditions of an if statement, and the curly brackets are used to state the operation which follows that condition. Except for the nested else condition in bold, where the else statement is followed by a round brackets enclosing the print command.
In programming, curly braces (the { and } characters) are used in a variety of ways. In C/C++, they are used to signify the start and end of a series of statements. In the following expression, everything between the { and } are executed if the variable mouseDOWNinText is true.
Different programming languages have various ways to delineate the start and end points of a programming structure, such as a loop, method or conditional statement. For example, Java and C++ are often referred to as curly brace languages because curly braces are used to define the start and end of a code block.
A scope in any programming is a region of the program where a defined variable can have its existence and beyond that variable it cannot be accessed. There are three places where variables can be declared in C programming language − Inside a function or a block which is called local variables.
Yes, because this has the advantage that any local variables in that block will be destroyed at the end of the block. This is especially useful if you have some kind of scope guard that you want to release as soon as possible, e.g.,
{ std::lock_guard<std::mutex> lock(the_mutex); // use protected objects } // release the_mutex
Note, however, that the use of a scope block like this is indicative of your code needing to be refactored: the contents of the block can usually be split out into a separate function, which can be named and reused.
I have found another use case in my own code: unit testing destructors. Example using UnitTest++ (but the same principle applies regardless of unit testing framework):
TEST(SomeTest) { { SomeClass someObject; } // someObject is destroyed CHECK(isSomeClassDestructorWorking()) // e.g. have all resources been freed up? }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With