例如:
if (true) try
{
// works as expected with both true and false, but is it legal?
}
catch (...)
{
// ...
}
换句话说,将try-block 放在if条件之后是否合法?
最佳答案
try
block (在 C++ 中是 statement)的语法是
try compound-statement handler-sequence
而if
的语法是:
attr(optional) if ( condition ) statement_true
attr(optional) if ( condition ) statement_true else statement_false
地点:
statement-true
- any statement (often a compound statement), which is executed if condition evaluates to true
statement-false
- any statement (often a compound statement), which is executed if condition evaluates to false
所以是的,您的代码是 C++
中的合法代码。
statement_true
在你的情况下是一个 try
block 。
在合法性上,类似于:
if (condition) for(...) {
...
}
但是您的代码可读性不强,并且在添加 else
时可能成为某些 C++ 陷阱的受害者。因此,在您的情况下,建议在 if
之后添加显式 {...}
。
关于c++ - if (condition) try {...} 在 C++ 中合法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35985592/