C - 大括号用法,不带函数名称

  • 本文关键字:函数 用法 c g-wan
  • 更新时间 :
  • 英文 :


可能的重复项:
C
语言中额外大括号的实际应用 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 寄存器用于其他任务非常有用)。

如您所见,定义范围可以具有外观和技术用途。两者都很有用。

为 {} 中的局部变量创建新作用域

例如在C

fun(){ 
  int i;   // i -1
  {
    int i;   // i -2 its new variable 
  }
}

最新更新