if/else 与三元运算符

发布于 2024-08-09 20:47:48 字数 161 浏览 6 评论 0原文

考虑到评估时间,以下两个是否等价?

if(condition1)
{
    //code1
}
else
{
    //code2
}

<代码>条件1? code1 : code2

或者它们只是语法上不同?

Considering the evaluation time, are following two equivalent?

if(condition1)
{
    //code1
}
else
{
    //code2
}

condition1 ? code1 : code2

Or they are just syntactically different?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

暮色兮凉城 2024-08-16 20:47:48

不同之处在于,后一个站可用于根据条件返回值

例如,如果您有以下语句:

if (SomeCondition())
{
    text = "Yes";
}
else
{
    text = "No";
}

使用三元运算符,您将编写:

text = SomeCondition() ? "Yes" : "No";

注意第一个示例如何根据条件执行语句,而第二个示例返回一个值< /em> 基于条件。

The difference is that the latter station can be used to return a value based on a condition.

For example, if you have a following statement:

if (SomeCondition())
{
    text = "Yes";
}
else
{
    text = "No";
}

Using a ternary operator, you will write:

text = SomeCondition() ? "Yes" : "No";

Note how the first example executes a statement based on a condition, while the second one returns a value based on a condition.

沧桑㈠ 2024-08-16 20:47:48

嗯...在前一种情况下,您可以使用任意数量或类型(表达式与语句)的代码来代替 code1code2。在后一种情况下,它们必须是有效的表达式。

Well ... In the former case, you can have any amount or type (expression vs statement) of code in place of code1 and code2. In the latter case, they must be valid expressions.

流星番茄 2024-08-16 20:47:48

是的&是的。

唯一的好处就是节省代码行数。

Yes & Yes.

Only profit is to save lines of code.

谁的年少不轻狂 2024-08-16 20:47:48

是的,这是两种不同的语法形式,并且工作方式相同,并且编译器将发出最有可能相同的代码。

Yes, these are two different syntactical forms and will work identically and most likey identical code will be emitted by the compiler.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文