Scope with Brackets in C++

Scope with Brackets in C++

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.

Why enclose blocks of C code in curly braces?

Legacy code needed { } in order to do declarations at all

In C89, you couldn't just do int i; anywhere; declarations were only valid at the beginning of blocks.

So:

a = 1;
int i; /* error */
i = 2;

...wasn't valid, but

a = 1
if (e) {
int i;

...was fine, as was a plain block.

The resulting style continued even after declarations became valid (C99) block-item(s), partly by inertia, partly for backwards portability, and also because it makes sense to establish a scope for new declarations.

Do you use curly braces for additional scoping?

I do if I am using a resource which I want to free at a specific time eg:

void myfunction()
{
{
// Open serial port
SerialPort port("COM1", 9600);
port.doTransfer(data);
} // Serial port gets closed here.

for(int i = 0; i < data.size(); i++)
doProcessData(data[i]);
etc...
}

How do curly braces and scope wоrk in C?

The while, if, else if, and else are followed by a single statement. This statement can be an actual line of C, or a block statement (surrounded by braces). The if, else if, and else are considered as one block.

So using braces, this would be the equivalent:

while((c = getchar())) != EOF) {
if (c >= '0' && c <= '9') {
++ndigit[c-'0'];
}
else if() { /*and so forth...*/
++nwhite;
}
else {
++nother;
}
}

In C, do braces act as a stack frame?

No, braces do not act as a stack frame. In C, braces only denote a naming scope, but nothing gets destroyed nor is anything popped off the stack when control passes out of it.

As a programmer writing code, you can often think of it as if it is a stack frame. The identifiers declared within the braces are only accessible within the braces, so from a programmer's point of view, it is like they are pushed onto the stack as they are declared and then popped when the scope is exited. However, compilers don't have to generate code that pushes/pops anything on entry/exit (and generally, they don't).

Also note that local variables may not use any stack space at all: they could be held in CPU registers or in some other auxiliary storage location, or be optimized away entirely.

So, the d array, in theory, could consume memory for the entire function. However, the compiler may optimize it away, or share its memory with other local variables whose usage lifetimes do not overlap.

What is the use extra curly brackets in the code? What does it do?

There are no "unwanted braces" in this code. There is an anonymous block, which is not an error. In fact, it is allowed by the spec.

Your variable k is defined in the main scope, but then shadowed in the anonymous block.

int main() {
int k = 0;
{
int k = 1;
// do more stuff with k
}
// k is still 0 here.
}

When I was programming C, something like 1000 years ago, I would have had stern words for a dev on my team who tried using this trick.

Variable declaration inside curly braces

The scope of a local variable is limited to the block between {}.

In other words: outside the block containing int a=3; a is not visible.

#include<stdio.h>
int main()
{
{
int a=3;
// a is visible here
printf("1: %d", a);
}

// here a is not visible
printf("2: %d", a);

{
// here a is not visible either
printf("3: %d", a);
}

return 0;
}

Hint: google c scope variables

Practical use of extra braces in C

Enclosing a code in braces { } creates an Scope.

Creating an local scope can have number of reasons like:

  • Allows you to reuse a variable name in enclosing scope.
  • Define variables in middle of function.

    Creating variables anywhere except at the start of an scope was not allowed in c89, but it is allowed since c99.

Online Example Code Sample:

#include<stdio.h>

int main()
{
int i = 10;
{
int i = 5;
printf("i is [%d]\n",i);
}
printf("i is [%d]\n",i);

return 0;
}

In your example code,

the extra { & } do not serve any purpose, they are just redundant code.

As @Martin suggests in comments, since enclosing code in {{{ & }}} is just similar to { & }, it might be used as an tag/pattern for easy search.

However, Personally, I would prefer adding appropriate comment to the code with an keyword which would show up in search rather than add such redundant code.

Can scopes be wrapped in parentheses and return a value in C?

This is a GCC extension to standard C called Statement Expressions. Yes, you can use it if you only need to support GNU compilers (and it is cross-platform). If you need to stick to standard C, you won't use the notation.



Related Topics



Leave a reply



Submit