以前没有任何关键字的{}的目的是什么
What is the purpose of {} without any keyword before?
今天,我花了4个小时调试了一个小错误:
while (++i < nb); //Notice this semicolon that i put by mistake
{
do_stuff();
}
我不知道do_stuff为什么没有执行足够的次数。当我看到我的错误时,我想知道:为什么有人会把代码放在函数中间的大括号里??有人能解释一下吗?C语言就是这样进化的吗?(我知道由于复古兼容性的原因,C的BNF包含了一些奇怪的东西)你认为循环中的预增是件坏事吗?我应该像上面那样写?
while (i < nb)
{
do_stuff();
i += 1;
}
为什么有人会把代码放在函数中间的大括号里??
这一点都不奇怪,但它引入了一个范围,如以下示例所示:
void foo () {
int a;
{ // start a new scope
int b = 1;
std::cout << b << std::endl;
} // end of scope, i.e. b is out of scope now
std::cout << a << std::endl;
std::cout << b << std::endl; // error: unknown variable b !!
double b = 0.0; // just fine: declares a new variable
}
您可以使用它来本地化函数内部变量的可访问性。在示例中,b
是一个临时的,通过将其声明放在本地作用域中,我可以避免在函数作用域中滥发变量名。
您可能希望将所有逻辑都放在while中,并有意省略body。一些编译器会警告你这一点,比如clang:
main.cpp:18:17: warning: while loop has empty body [-Wempty-body]
while (++i < nb); //Notice this semicolon that i put by mistake
^
main.cpp:18:17: note: put the semicolon on a separate line to silence this warning
引入本地作用域,如:
{
SomeClass aa;
// some logic
}
你可能希望,在上面的例子中,有人可能希望在大括号之前调用一个析构函数,也就是说,它会释放一些资源。
我相信最常见的用途是与RAII:一起使用
{
std::lock_guard<std::mutex> lock(mutex);
// code inside block is under mutex lock
}
// here mutex is released
本地作用域有意义限制对象的生存时间和作用域。它们对switch
/case
语句至关重要:
switch (i){
case 1:
std::string s;
case 2:
//does s exist or not? depends on the value of i
}
C++说这是直接非法的。为了解决这个问题,你引入了一个本地作用域:
switch (i){
case 1:
{
std::string s;
}//the lifetime of s ends here
case 2:
//s is inaccessible
}
现在s
被限制在它的范围内,并且您解决了s
有时被定义的问题。
您可以添加任意数量的本地块,例如,这很好:
int main(){{{{{{{{{{
}}}}}}}}}}
{<statement>*}
(*表示零或更多)是C/C++中的代码块,被视为单个语句。语句类似于if (<expression>) <statement>
(注意:这是一个递归语句)。另一个语句可以是<expression>;
。
此外,{}
生成一个新的作用域。
这也是为什么可以在if
语句中给出多个语句的原因。
如果有帮助,您可以将它们视为内联函数,并可以访问当前范围。(不是正确的查看方式,但距离足够近)
看看@tobi303的回答作为一个例子。
- 当我从下面的代码中删除关键字 virtual 时,它可以正常工作,否则会出现错误。在这里"virtual"字的意义是什么?
- 这个额外的关键字在这个 c++ 类声明中是什么意思?
- "friend"关键字在C++中是什么意思?
- 关键字使用的功能是什么?
- 统一初始化是隐式发生的,即使 int 强制转换运算符是使用 explicit 关键字声明的.原因是什么?
- ELI5 函数名称后面的"&&"关键字是什么意思
- 在 Objective-C++ 中应用于__weak指针时,通过关键字推导类型"auto"规则是什么?
- 内联函数 - 相对于内联关键字,它们到底是什么
- C++中"using"关键字背后的逻辑是什么?
- c++ 类访问关键字"signals"是什么意思?
- CppUTest中extern关键字的替代方案是什么
- 摩西源代码中的关键字可变是什么?
- C++中的"and"、"or"等关键字的目的是什么?
- 函数参数之前的类关键字是什么
- "signed"关键字的实际用途是什么?
- 关键字"value"是什么意思?
- 以前没有任何关键字的{}的目的是什么
- 这里的unsigned关键字的作用是什么
- 当已经有"struct"时,在C++中包含'class'关键字的原因是什么?
- c++函数签名的附加关键字是什么