C# float++ and float-

Asked

Viewed 75 times

4

I used the following code snippet:

bool plus = false;
int index = 0;

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

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

index += plus ? 1 : -1;

Someone has an explanation for this?

  • 4

    I guess what I wanted to do was index = plus ? index+1 : index-1; instead of using pre- and post-increment operators

  • 4

    Complementing what @Isac said: the post-decrement operator works like this: it takes the value of the variable, puts a copy of that value to be used in the operation and increments/decreases the variable, keeping the copy intact; then it executes the operation. In your case, the following occurs: (1) copies the value of index (which is 0) on something temporary (2) increments/decreases index (which goes to +1 or -1), keeping your copy intact (3) assigns to index the operand (that is 0), which ultimately cancels the side effect of the post increment/decrease operator

  • Now I realized, I had already solved with the second example of the question, but to test I used the pre-aincrement/ decrement and it worked, thank you very much for the explanation!

1 answer

7


What the post increment operator does?

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

Explaining what happened in your code

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

What can you do?

  • You can do as you showed the @Isac

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

  • Or you can use the preincrement. This way you will be creating and changing the value of the associated copy, and only then will you do the attribution.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.