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 16:05

A block is a scope that determines the lifetime of variables, as well as their visibility to the compiler. So variables that get created within a block go away when control exits the block.

It can be very handy when those variables are instances of classes with constructors and destructors.

However, in your example there is not much advantage.

查看更多
叛逆
3楼-- · 2019-01-03 16:07

It is creating a scope. Stack objects are destroyed when they go out of scope. It looks like it is doing some sort of typing, which would mean each block is something that they wanted to time. However, I don't see any scoped timer objects, so, yeah, makes no sense.

查看更多
ゆ 、 Hurt°
4楼-- · 2019-01-03 16:07

Hmm - I'm maybe off the chart here but I think local variable define inside such block will not be valid outside of the block

查看更多
登录 后发表回答