如果(条件)尝试 {..} 在C++合法
Is if (condition) try {...} legal in C++?
例如:
if (true) try
{
// works as expected with both true and false, but is it legal?
}
catch (...)
{
// ...
}
换句话说,将 try-block 放在 if 条件之后是否合法?
try
块(这是C++中的语句)的语法为
try compound-statement handler-sequence
if
的语法是:
attr(optional) if ( condition ) statement_true
attr(optional) if ( condition ) statement_true else statement_false
哪里:
statement-true
- 任何语句(通常是复合语句),其中 如果条件计算结果为 truestatement-false
则执行
- 任何 语句(通常是复合语句),在 if 条件下执行 计算结果为 false
所以是的,您的代码是 C++
中的合法代码.
在您的情况下statement_true
是一个try
块。
在合法性上,它类似于:
if (condition) for(...) {
...
}
但是您的代码不是很好读,并且在添加else
时可能会成为一些C++陷阱的受害者。因此,建议您在if
后添加显式{...}
。
将 try-block 放在 if 条件之后是否合法?
这是合法的。您的代码与以下内容相同(最好编写为):
if (true) {
try
{
// works as expected with both true and false, but is it legal?
}
catch (...)
{
// ...
}
}
因此,如果条件false
则不会执行try-catch
块。如果这是您所期望的,那很好。
是的。if
的大括号是可选的。想象一下,您在try { .. } catch { .. }
周围{}
。
您可能会感兴趣,当您写if
/else if
/else
时,就会发生这种情况;C++实际上没有else if
... 所以这个:
if (A) {
}
else if (B) {
}
实际上解析为:
if (A) {
}
else
if (B) {
}
这是:
if (A) {
}
else {
if (B) {
}
}
它的格式很好。try-blocks 是符合 [stmt.stmt]/1 的语句 s,语句 s 是按照 [stmt.select]/1 遵循的语句if (…)
。
相关文章:
- std::vector::迭代器是否可以合法地作为指针
- 为constchar*定义std::begin合法吗
- 新分配指向函数的指针是否合法?
- 将类型声明为类型模板参数的模板参数的一部分是否合法?
- 在 nullptr 上调用无状态类的非静态成员函数是否合法?
- 如果 iostream 对象不可复制,为什么以下代码是合法的?
- 在 constexpr 构造函数中初始化数组是否合法?
- 如何检查 int 变量是否包含合法(非陷阱表示)值?
- 在 // C++注释中使用 \\ 是否合法?(C++评论中的LaTeX方程)
- 存储对(可能)临时对象的引用是否合法,只要引用不比对象存活?
- 我想知道为什么"std::unique_ptr<int> foo(新 int)"是合法的,因为"std::<int>unique_ptr"要求输入参数类型应该是"int"?
- 将可变参数类型列表的扩展打包为复杂类型的初始值设定项列表 - 合法吗?
- Lambda回归:这合法吗?
- 使用 Rcpp 加速替换迭代算法中的列表和向量元素是否合法?
- 返回 Eigen::Ref 合法吗?
- 截至 C++14 起尾随返回类型语法的合法使用
- 将基本实例指针强制转换为派生实例指针是否合法?(实例不是派生实例)
- 对静态分配的子类对象进行静态分配的纯虚拟父类引用是否合法?
- 将基本类型数组中的内存重新用于不同(但仍然是基本)类型的数组合法吗
- glVertexAttribPointer调用中强制转换为void*是合法的C++吗