为什么将 C 代码块括在花括号中? [英] Why enclose blocks of C code in curly braces?

查看:24
本文介绍了为什么将 C 代码块括在花括号中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在查看一些 C 代码,并注意到它在代码块周围充满了这些花括号,没有任何类型的控制结构.看一看:

I am looking at some C code, and have noticed it is full of these curly braces surrounding blocks of code without any sort of control structure. Take a look-see:

//do some stuff . . .
fprintf(stderr, "%.2f sec
", (float)(clock() - t) / CLOCKS_PER_SEC);
{
    //a block! why not?
    char *tmp_argv[3];
    tmp_argv[0] = argv[0]; tmp_argv[1] = str; tmp_argv[2] = prefix;
    t = clock();
    fprintf(stderr, "[bwa_index] Convert nucleotide PAC to color PAC... ");
    bwa_pac2cspac(3, tmp_argv);
    fprintf(stderr, "%.2f sec
", (float)(clock() - t) / CLOCKS_PER_SEC);
}

为什么要在代码中插入这样的块?里面塞满了它们.是否有某种性能优势?一些神秘的 C 语言?为什么???

Why would you insert blocks like this in the code? It is chock full of 'em. Is there some kind of performance benefit? Some mystical C thing? Why???

此代码来自 BWA,这是一个对齐的生物信息学程序小序列使用 Burrows-Wheeler 变换,以防万一你们当中有人想知道.此代码示例与应用程序的功能不是特别相关.

edit: This code if from BWA, a bioinformatics program that aligns small sequences to large reference ones using the Burrows-Wheeler transform, in case any of you were wondering. This code example isn't particularly relevant to the functionality of the application.

推荐答案

需要遗留代码 { } 才能进行声明

在 C89 中,您不能只在任何地方执行 int i;;声明仅在块的开头有效.

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.

所以:

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

...无效,但是

a = 1
if (e) {
  int i;

...很好,就像一个普通的方块一样.

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

即使在声明生效(C99)block-item(s) 之后,结果样式仍然存在,部分原因是惯性,部分原因是向后可移植性,还因为为 new 建立一个范围是有意义的声明.

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.

这篇关于为什么将 C 代码块括在花括号中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆