Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
853 views
in Technique[技术] by (71.8m points)

vb.net - 'If' statement and the colon

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...