Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
926 views
in Technique[技术] by (71.8m points)

scope - Why enclose blocks of C code in curly braces?

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);
}

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.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...