簡體   English   中英

你能用C做裸塊嗎?

[英]Can you have a bare block in C?

我知道在C#和JavaScript中,以下內容完全有效:

{
  var foo;
}

是否有一個在C中有效的裸塊?

即這是有效的C?

{
  int foo;
}

這在C中也有效嗎?

是的,它是,它被稱為復合語句

從C11標准:

6.8.2 Compound statement
Syntax
1 compound-statement:
    { block-item-listopt }
block-item-list:
    block-item
    block-item-list block-item
block-item:
    declaration
    statement

復合語句本身就是C 語句

例如,此塊是有效塊:

{
    {
        {
            printf("Hello world");
        }
    }
}

即便是這個也是有效的:

{{{}}}

{}是一個空的復合語句。

是的,它完全沒問題!

舉個例子:

#include <stdio.h>

int main() {

{   
    int i = 5;  //If you declare i outside you can use both print statements
    printf("%d", i);
}


//printf("%d", i);  Note that i is out of scope here

    return 0;

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM