是否(条件)尝试{...}在C ++中合法? [英] Is if (condition) try {...} legal in C++?

查看:125
本文介绍了是否(条件)尝试{...}在C ++中合法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:

if (true) try
{
    // works as expected with both true and false, but is it legal?
}
catch (...)
{
    // ...
}

换句话说,在if条件之后放置try-block 是否合法?

In other words, is it legal to put the try-block right after the if condition?

推荐答案

try 块的语法(这是一个语句

The syntax of a try block (which is a statement in C++) is

try compound-statement handler-sequence

如果是:

attr(optional) if ( condition ) statement_true      
attr(optional) if ( condition ) statement_true else statement_false     

其中:


statement-true - 任何语句(通常是复合语句),如果条件求值为true,
执行
statement-false - 任何
语句(通常是复合语句),这是执行如果条件
评估为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 ++

So yes, your code is legal code in C++.

statement_true 在你的情况下是一个 try block。

statement_true in your case is a try block.

在合法性方面,它类似于:

In legality, it is similar to:

if (condition) for(...) {
    ...
}

您的代码不是很可读,并且当添加 else 时,可能会成为某些C ++陷阱的受害者。所以,建议在之后添加 {...} ,如果在你的情况下。

But your code is not very readable and can be the victim of some C++ pitfalls when an else is added. So, it is advisable to add explicit {...} after if in your case.

这篇关于是否(条件)尝试{...}在C ++中合法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆