'如果'声明和冒号 [英] 'If' statement and the colon

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

问题描述

以下是一段有趣的代码,我的团队成员对此进行了一次稍微激烈的讨论......

  Dim fred As Integer 

如果为True则fred = 5:fred = 3:fred = 6 Else fred = 4:fred = 2:fred = 1

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



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



这是一个非常人为的代码示例,最初是作为使用带有If语句的冒号的示例,但是然后有人决定自己为 fred 提供结果。



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

解决方案

我'假设您的意思是VB.Net。



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



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



结果应为6。



这是因为行if语句的语法是:

 如果是BooleanExpression则语句[Else Statements] StatementTerminator 

和语句被定义为

 陈述:: = 
[陈述] |
声明:[声明]

修改:
我想注意调试代码不是作弊。



我曾经在微软的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天全站免登陆