C # float ++ and float--

4

I used the following code snippet:

bool plus = false;
int index = 0;

index = plus ? index++ : index--;

The index result is 0 and I do not know why, when I do the form below it works:

index += plus ? 1 : -1;

Does anyone have an explanation for this?

    
asked by anonymous 01.08.2018 / 11:17

1 answer

5

What does the post-increment operator do?

As already explained by @Jefferson Quesado . When you use for example index++ you are making a call to a function that will create an associated copy.

Explaining what happened in your code

Since you are a post increment operator, you first assign your variable index and then increment the copy.

What can you do?

  • You can do as shown by @Isac
      

    index = plus ? index+1 : index-1;

  • Or, you can use the pre increment operator. This way you will be creating and changing the value of the associated copy, and then you will do the assignment.

    index = plus ? ++index : --index;

01.08.2018 / 12:36