hoythan
V2EX  ›  C

C 语言 while 中 两个花括号有什么特别意义吗?

  •  
  •   hoythan ·
    PRO
    · Jul 4, 2018 · 3621 views
    This topic created in 3062 days ago, the information mentioned may be changed or developed.

    看到别人的代码中

    while(xxx)
    {
    	{
        	xxxx
        }
    }
    

    这是某种特定要求的写法吗?

    xiongjia
    xiongjia
    Jul 4, 2018❤️1
    1
    C++ 中增加一个 Block Scope 可以用来控制变量或对象的范围: https://en.cppreference.com/w/cpp/language/scope

    C 里应该类似吧。
    inoki
    inoki
    Jul 4, 2018❤️1
    2
    控制内部新声明变量生命周期和作用范围
    比如
    while (xxx)
    {
    {
    int i=0;
    i++; // OK
    }
    i=4; // Undefined identifier
    }
    bp0
    bp0
    Jul 4, 2018❤️1
    3
    其实是 C89 中只准许在作用域的开始处声明变量。所以如果想在函数中间中间定义变量,只能加大括号。当然副作用是从大括号出来以后变量就不能用了。就像#2 说的那样。

    C99 以后可以随便定义了,不过为了兼容 C89 的编译器,所以大部分代码还是会使用大括号。

    不过,在 while{的起始处是可以定义变量的,如果在前 2 个“{”之间没有语句,那么感觉中间的{}是没有意义的。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1903 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 12:01 · PVG 20:01 · LAX 04:01 · JFK 07:01
    ♥ Do have faith in what you're doing.