2

What is the purpose of brackets {} in C code without the usage of control structures like loops, if-else, function calls etc. ?

An example can be this:

    // Add UDP transport.
    {
        // Init transport config structure
        pjsua_transport_config cfg;
        pjsua_transport_config_default(&cfg);
        cfg.port = 5080;

        // Add TCP transport.
        status = pjsua_transport_create(PJSIP_TRANSPORT_UDP, &cfg, NULL);
        if (status != PJ_SUCCESS) error_exit("Error creating transport", status);
    }

Is this just to show that this is a way to split your code into semantic blocks during a long function? And if so, wouldn't it be cleaner to make this into an own function?

The code can be found in this blog: Xianwen's blog

Nerethar
  • 327
  • 2
  • 16
  • you are right, that partly answered my question. Thank you, I searched for a post like this, but found nothing. Now I still wonder if this seems to be a good style or not. In my oppinion it would be smarter to have subfunctions rather than cutting one large function into artificial scopes. – Nerethar Nov 02 '15 at 16:16

1 Answers1

2

With the brackets you create a block of code. In the block, you can declare new variables. Those variables only have scope in the block and they cease to exist if the block is exited.

Paul Ogilvie
  • 25,048
  • 4
  • 23
  • 41
  • Thank you for your answer, but why would you do this instead of creating own functions for some parts? – Nerethar Nov 02 '15 at 16:17
  • There can be many reasons. Take for example a long switch statement (e.g. to process Windows messages), then it can be easier to quickly create some variables to handle the message than to create an own funcion. – Paul Ogilvie Nov 02 '15 at 16:24