Possible Duplicate:
Practical use of extra braces in C
Unnecessary curly braces in C++?
大括号的用法如下:

int var;
{
  some coding...
  ...
}

大括号前没有函数名,也没有typedef等。
更新时间:
我在gwan sqlite.c示例中找到了这段代码,http://gwan.com/source/sqlite.c
我部分引用如下:
...some coding
sqlite3_busy_timeout(db, 2 * 1000); // limit the joy

   // -------------------------------------------------------------------------
   // create the db schema and add records
   // -------------------------------------------------------------------------
   {   //<-- here is the starting brace
      static char *TableDef[]=
      {
         "CREATE TABLE toons (id        int primary key,"
                             "stamp     int default current_timestamp,"
                             "rate      int,"
                             "name      text not null collate nocase unique,"
                             "photo     blob);",
         // you can add other SQL statements here, to add tables or records
         NULL
      };
      sqlite3_exec(db, "BEGIN EXCLUSIVE", 0, 0, 0);
      int i = 0;
      do
      {
         if(sql_Exec(argv, db, TableDef[i]))
         {
            sqlite3_close(db);
            return 503;
         }
      }
      while(TableDef[++i]);

      // add some records to the newly created table
      sql_Exec(argv, db,
               "INSERT INTO toons(rate,name) VALUES(4,'Tom'); "
               "INSERT INTO toons(rate,name) VALUES(2,'Jerry'); "
               "INSERT INTO toons(rate,name) VALUES(6,'Bugs Bunny'); "
               "INSERT INTO toons(rate,name) VALUES(4,'Elmer Fudd'); "
               "INSERT INTO toons(rate,name) VALUES(5,'Road Runner'); "
               "INSERT INTO toons(rate,name) VALUES(9,'Coyote');");

      sqlite3_exec(db, "COMMIT", 0, 0, 0);

      // not really useful, just to illustrate how to use it
      xbuf_cat(reply, "<br><h2>SELECT COUNT(*) FROM toons (HTML Format):</h2>");
      sql_Query(argv, db, reply, &fmt_html, "SELECT COUNT(*) FROM toons;", 0);
   } //<-- here is the ending brace
...some coding

最佳答案

不带函数名的大括号用法
我想答案不在于什么,而在于为什么要这样做。
例如,您可以使用不同的类型(SQLite示例这样做是为了在从头重新启动时使用相同的术语,而不是冒命名冲突的风险),重新使用变量名来执行其他操作:

{
   int i = 2;
   ...
   {
      int i = 10; // this is a different variable

      // the old value of 'i' will be restored once this block is exited.
   }
}
{
   void *i = alloca(16 * 1024); // this memory will be freed automatically
   ...                          // when the block will be exited
}

但这也允许您释放在堆栈上分配的alloca()内存,就像上面所做的那样。
对于编译器来说,这也是一个明确的指示,即不再需要块中定义的变量(这有助于确保为其他任务释放CPU寄存器)。
如您所见,定义范围可以具有外观和技术用途。两者都有用。

09-06 15:13