2

我在 C 函数的定义中(在动态窗口管理器的源代码中)发现了一个块的奇怪用法。

它是函数定义中的一个块。该文件的第 944 行有一个示例。这是关于什么的?

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

2 回答 2

12

很简单:一个块。它引入了一个新的有限作用域:在内部声明的变量不能在外部使用,因此它可以用来限制一组变量的作用域。

但通常它只是用于组织代码以提高可读性,也许是为了建议或提醒一些额外的细节(或者只是为了从你的编辑器中强制额外的缩进级别),例如:

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


}
unlockDatabase();

此外,较旧的 C 标准仅将变量声明限制在块的开头。在该限制下,您的选择是在函数或其他(阻塞)控制结构的开头声明所有变量,或者仅出于声明其他变量的目的而引入新的裸块。

于 2012-07-07T23:44:18.893 回答
1

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
于 2012-07-09T05:09:37.013 回答