0

I have created a minimal example reproducing the problem (or rather my misunderstanding):

string text = @"eaisjdoaisjdoaisjdai_osjdaisodjasizzi_ojiozaziasjz_";
int[] score = new int[123];

foreach(char letter in text)
{
   int val = score[letter]; //give me the value stored at the index
   score[letter] = val++; //increment it and store it back into the array at the index
}

...

Debugging through the above, val is correctly being assigned the value at the specified index of the array. But when incremented, val is not assigned back into the array. Why is that?

The picture shows the immediate window evaluating the value of val when retrieving it from the array, the value of score[letter] after being assigned to and also the incremented value of val

I'm clearly doing something stupid but can't quite figure out what.

enter image description here

3
  • you should change that to a for loop, it looks like you are indexing into your array by the character. Are you sure you want that? Commented Jan 16, 2016 at 19:03
  • If the val is not being used inside the loop, you can simply write score[letter]++ or score[letter] += 1 to increment the value. Creating the variable val without using it is a bit confusing here. Commented Jan 16, 2016 at 19:16
  • @ohw The reason for putting it into a variable was for debugging purposes. Commented Jan 16, 2016 at 19:18

1 Answer 1

3

This is because you are using the post-increment operator, which increments the value after returning it.
Change it to the pre-increment operator ++val and it should work.

From the ++ operator documentation:

The first form (++val) is a prefix increment operation. The result of the operation is the value of the operand after it has been incremented.

The second form (val++) is a postfix increment operation. The result of the operation is the value of the operand before it has been incremented.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.