简体   繁体   English

C块内部有什么功能?

[英]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). 我在C函数的定义中发现了一个奇怪的块使用(在动态窗口管理器的源代码中)。

It's a block inside the definition of a function. 它是函数定义中的一个块。 Line 944 of this file has an example. 该文件的第944行有一个例子。 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. 此外,较旧的C标准仅将变量声明限制在块的开头 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. C块的用法是将逻辑与其余代码分开。 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. 在C语言中,变量只能在函数的开头声明。 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 因此,任何需要更多变量并且不希望与函数的其余代码具有单独功能的代码片段都可以放在代码块中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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