|
-
Feb 3rd, 2010, 12:35 PM
#1
Thread Starter
Frenzied Member
[RESOLVED] c# Incrementors
Hi,
Why do the following code fragments not behave the same way? In Java I'm quite sure the two would behave the same.
Code:
for (; BufferPos < BufferLen; BufferPos++)
{
if (ReadBuffer[BufferPos] == search[0])
{
found = true;
break;
}
}
Code:
while (BufferPos < BufferLen)
{
if (ReadBuffer[BufferPos++] == search[0])
{
found = true;
break;
}
}
-
Feb 3rd, 2010, 01:09 PM
#2
Re: c# Incrementors
It has to do with when the variable is incremented... On that second one, if you use ++BufferPos, you might find that it then does work as expected.
Let's say BufferPos is 10... in the first example, BufferPos is incremented at the top of the loop, to 11, so you get ReadBuffer[11] ....
In the second example, it will use BufferPos FIRST, THEN increment it after the fact.... so you end up using BufferPos[10]... BufferPos[11] doesn't get used until the next loop through.
to see how it varies try something along these lines:
Code:
int a,b,c;
a = 1; //a = 1
b = a++; // a = 2; b = 1 (a is incremented after the value is assigned to b)
c = ++a; // a = 3; c = 3 (a is incremented first, then assigned to c)
That was something I had trouble getting my head around at the time.
-tg
-
Feb 3rd, 2010, 08:34 PM
#3
Re: c# Incrementors
In a 'for' loop, the loop variable isn't incremented at the beginning of the loop. It's incremented at the end, and that's your problem.
In the first code snippet the loop variable is incremented at the end of the loop, but when you find a match you hit a 'break' so the end of the loop isn't reached on that iteration. In the second code snippet you increment the variable immediately after use, before you hit the 'break'.
I think you'll find that Java would work the same way. It certainly should because a 'break' statement should break out of the loop immediately.
Last edited by jmcilhinney; Feb 3rd, 2010 at 08:40 PM.
-
Feb 4th, 2010, 05:22 AM
#4
Thread Starter
Frenzied Member
Re: c# Incrementors
Yeah it does work as expected in c#. I didn't see my issue until after I've looked at it again after my 2 hour commute home.
The reason while loop version was failing is that BufferPos was incremented when I found a match which it shouldn't have.
One of those freak logic issues that is so below the radar that I miss it.
And I think I was doing some step through debugging the wrong way or something. Not quite familar with .NET IDE so much!
Thanks guys!
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|