Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

RCS1089: += 1 is not always equivalent to postfix increment #639

Closed
jhinder opened this issue Feb 4, 2020 · 3 comments
Closed

RCS1089: += 1 is not always equivalent to postfix increment #639

jhinder opened this issue Feb 4, 2020 · 3 comments

Comments

@jhinder
Copy link

jhinder commented Feb 4, 2020

public class C {
    int i;
    
    public int M()
    {
        i += 1; // <-- equivalent to i++
        return i += 1; // <-- equivalent to ++i!
    }
}

Sharplab

Whenever the value of the += expression is taken, it's equivalent to a pre-increment, not a post-increment. When applying the code fix RCS1089, this difference can introduce subtle off-by-one bugs.

Version: 2.3.0

@josefpihrt
Copy link
Collaborator

It's the same with yield return.

SharpLab

Do you know of any other syntax where the pre-increment should be used?

@jhinder
Copy link
Author

jhinder commented Feb 4, 2020

Passing arguments (M(i += 1)), array indexing (a[i += 1]) -- basically anything where the += expression is used as an expression and not just a statement, by the looks of it.

And of course it's not just the increment operator, this affects the decrement operator as well.

@josefpihrt
Copy link
Collaborator

I came to this conclusion:

If an assignment expression is used as a part of statement, post-increment should be used:
i += 1; > i++;

Every other use of i += 1 should be replaced with pre-increment.

Same logic applies to decrement operation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants