Why enclose blocks of C code in curly braces?

2019-01-03 15:05发布

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\n", (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\n", (float)(clock() - t) / CLOCKS_PER_SEC);
}

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???

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.

9条回答
仙女界的扛把子
2楼-- · 2019-01-03 15:42

Is that all of it? Maybe the programmer is using tmp_argv somewhere else in the code. I can't think of any other reason since the tmp_argv between the { and } is separate from any outside the braces.

查看更多
Bombasti
3楼-- · 2019-01-03 15:45

I sometimes use blocks in these cases: - To localize variables - Or to easier to read ...

查看更多
唯我独甜
4楼-- · 2019-01-03 15:46

To scope variables. E.g. the variable tmp_argv will only be valid between the braces.

查看更多
forever°为你锁心
5楼-- · 2019-01-03 15:52

Another use case for this I've recently discovered is when you have open/close semantics and you want to clearly mark the 'inner' code:

f = fopen('file');
{
    // do stuff
}
fclose(f);

This works well to remind you to close/free objects and a makes the code somewhat cleaner.

查看更多
女痞
6楼-- · 2019-01-03 15:56

The variables that you declare inside the block are local to that block. This way you may be able to redefine tmp_argv in some other place of your code (below) without conflicting with this piece of code.

查看更多
神经病院院长
7楼-- · 2019-01-03 16:03

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.

查看更多
登录 后发表回答