-1

I am confused by the {} inside the main. Can someone please explain me their purpose? I do understand the code, but this is the first time I see this format.

Why are the {} necessary to this part of the code, or what is the use of {} inside a function? It is not to declare a nested function, or is it?

int main() 
{
    void *p1, *p2, *p3;
    arenaCheck();
    p1 = malloc(254);
    arenaCheck();
    p2 = malloc(25400);
    arenaCheck();
    p3 = malloc(254);
    printf("%llx %llx %llx\n", (long long)p1, (long long)p2, (long long)p3);
    arenaCheck();
    free(p2);
    arenaCheck();
    free(p3);
    arenaCheck();
    free(p1);
    arenaCheck();

    {   /* What is the purpose of these, what is this doing { } */
        struct timeval t1, t2;
        int i;
        getutime(&t1);
        for(i = 0; i < 10000; i++)
        if (malloc(4) == 0) 
        break;
        getutime(&t2);
        printf("%d *** malloc(4) required %f seconds\n", i, diffTimeval(&t2,&t1));
    }

    return 0;
}
Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
  • Have you removed them and compiled and ran it to see if there was any difference? – Cyrus Apr 22 '15 at 03:31
  • 1
    possible duplicate of [Why enclose blocks of C code in curly braces?](http://stackoverflow.com/questions/1677778/why-enclose-blocks-of-c-code-in-curly-braces) – Corb3nik Apr 22 '15 at 03:33

2 Answers2

3

Older versions of C (pre-C99) required variables to be declared at the start of a block. The declarations of t1 and t2 would cause an error if compiling this code for those C versions without the braces in place. If you're using C99 or newer, you can simply delete the braces - they're superfluous in this case.

Carl Norum
  • 219,201
  • 40
  • 422
  • 469
2

That's a block. It creates a lexical scope. The variables inside a block can't be used outside.

int main() {
    {
        int i = 5;
    }
    printf("i = %d\n", i); // error
}

They are also useful in old programs because, once upon a time, you had to put all variables at the top of a block.

In C++, the destructors will get called at the end of the block.

Dietrich Epp
  • 205,541
  • 37
  • 345
  • 415