문제

For the below FOR loop in VB.net (a simplified version of my code), the encased logic is only hit twice. I had assumed the end case being 10 and 50 would be interpreted as "continue if i < 10 AND i < 50" but that does not seem to be the case.

    For i As Integer = 0 To 10 And 50
      '...logic...
    Next

What is the correct interpretation, and is there a way to create a FOR loop with multiple end cases?

도움이 되었습니까?

해결책

Your loop is equivalent to

    Dim t = 10 And 50
    For i As Integer = 0 To t
        ' something '
    Next

where 10 And 50 is a bitwise AND operation on two Integer numbers. And because 10 And 50 returns 2 you get loop from 0 to 2.

다른 팁

Might And be bitwise and? 10 = 8+2, and 50 = 32+16+2, so the bitwise and would just be 2.

The syntax of the For statement is (edited to fit):

For LoopControlVariable Equals Expression To Expression [Step Expression ]

So the And keyword plays no special role in the statement, it is simply part of the To expression. With integral operands, it performs a mathematical AND operation that performs a bitwise AND on the bits in the integral value.

Since 10 And 50 equals 00001010 And 00110010 in binary = 00000010 in binary or 2 in decimal, the loops iterates from 0 to 2 inclusive.

What are you trying to accomplish? Why do you it to be for i<10 and i<50? Wouldn't you just need for i<50?

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top