“如果"语句和冒号 [英] 'If' statement and the colon

查看:32
本文介绍了“如果"语句和冒号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一段有趣的代码,我的团队成员刚刚就……进行了激烈的讨论……

 将 fred 调暗为整数如果为真则 fred = 5 : fred = 3 : fred = 6 否则 fred = 4 : fred = 2 : fred = 1

执行上述代码片段后,fred的值是多少?

尽量不要欺骗和调试代码.

这是一个精心设计的代码示例,一开始是将冒号与 If 语句结合使用的示例,但后来有人决定自己为 fred 提供结果.

更新:我通常不会编写这样的代码,此代码段仅用作示例.碰巧的是,这个问题起源于为我们的团队创建编码标准文档的讨论.

解决方案

我假设你指的是 VB.Net.

根据VB语言规范中的语法,您可以在这里阅读:

http:///www.microsoft.com/Downloads/thankyou.aspx?familyId=39de1dd0-f775-40bf-a191-09f5a95ef500&displayLang=en

结果应该是6".

这是因为line if 语句"的语法是:

If BooleanExpression Then Statements [ Else Statements ] StatementTerminator

和声明"被定义为

语句 ::=[声明] |声明:[声明]

我要注意的是,调试代码并不是作弊".

我曾经在 Microsoft 的 VB 编译器团队工作.

有时规范不明确,或者与我们实际交付的内容不符.在其中的几个案例中,解决方案(我们为修复它所做的)始终基于嗯……编译器现在做了什么".

有时我们会改变编译器,有时我们会改变规范.

然而,在我们做出决定之前,我们总是会运行编译器来看看它实际做了什么.

所以......调试代码是弄清楚它做什么的重要部分......

Here is an interesting piece of code that my fellow team members were just having a slightly heated discussion about...

  Dim fred As Integer

  If True Then fred = 5 : fred = 3 : fred = 6 Else fred = 4 : fred = 2 : fred = 1

After executing the above code snippet, what is the value of fred?

Try not to cheat and debug the code.

This is a highly contrived code example that started out as an example of using the colon with an If statement, but then someone decided to take it upon themselves to proffer a result for fred.

UPDATE: I would not normally write code like this and this snippet only serves as an example. As it so happens, this question originated from a discussion involving the creation of a coding standards document for our team.

解决方案

I'm assuming you mean VB.Net.

According to the grammar in the VB Language spec, which you can read here:

http://www.microsoft.com/Downloads/thankyou.aspx?familyId=39de1dd0-f775-40bf-a191-09f5a95ef500&displayLang=en

The result should be "6".

This is because the grammar for a "line if statement" is:

If  BooleanExpression  Then  Statements  [  Else  Statements  ]  StatementTerminator

and "statements" is defined to be

Statements  ::=
[  Statement  ]  |
Statements  :  [  Statement  ]

Edit: I would like to note that debugging the code is not "cheating".

I used to work on the VB compiler team at Microsoft.

There were times where the spec was ambiguous, or didn't match what we had actually shipped. In several of those cases the solution (what we did to fix it) was always based on "well... what does the compiler do now".

Sometimes we would change the compiler, sometimes we would change the spec.

However,we would always run the compiler to see what it actually did before we made a decision.

So... debugging the code is a big part of figuring out what it does...

这篇关于“如果"语句和冒号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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