简体   繁体   中英

C Block inside a function?

I found a strange use of a block in the definition of a C function (in the source of a dynamic window manager).

It's a block inside the definition of a function. Line 944 of this file has an example. What is this about?

void
grabbuttons(Client *c, Bool focused) {
  updatenumlockmask();
  {
    unsigned int i, j;
    unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask };
    //some more code
  }
}

It is simply that: a block. It introduces a new limited scope: variables declared inside aren't usable outside, so it can be used to limit the scope of a set of variables.

But often it's just used to organize code for readability, and perhaps to suggest or remind of some additional details (or simply to force an additional level of indentation from your editor), eg:

lockDatabase();
{
    // this code is all within the database lock:


}
unlockDatabase();

Furthermore, older C standards limited variable declarations to the beginning of a block only. Under that restriction, your choices are to declare all of your variables at the beginning of your function or other (blocked) control structure, or to introduce a new bare block solely for this purpose of declaring additional variables.

Usage of C blocks is to separate out a logic from the rest of the code. Following are some scenarios when this is useful:

  1. A function which shall not be called more than once. It is better to write that piece of code within the block.
  2. In C language, variables can be declared only in the beginning of a function. So, any piece of code which needs more variables and does not want a separate functionality from the rest of the code of the function can be put in the code block

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM