Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scope with Brackets in C++

Tags:

c++

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**** 
like image 657
schnozzinkobenstein Avatar asked Feb 22 '11 00:02

schnozzinkobenstein


People also ask

What is the use of brackets in C?

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.

What do curly brackets mean in C?

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.

Why do braces have curly C?

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.

What are scope rules in C?

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.


2 Answers

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.

like image 72
James McNellis Avatar answered Sep 19 '22 08:09

James McNellis


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? } 
like image 20
JBentley Avatar answered Sep 22 '22 08:09

JBentley