Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Difference between -= and =- in C++ and C?

I often confuse both "-=" and "=-", like what is the exact difference between them?

int main()
{
    int x=10, a=-3;
    x=-a;
    printf("%d",x);

    return 0;
}

Output

3

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

-= is a compound assignment operator. =- is two operators applied seperately.

While

a =- 3;

is the same as

a = (-3);

This

x -= a;

is more or less equivalent to

x = x - a;

"More or less" because operators can be overloaded (in C++) and typically the compound operator avoids the temporary right hand side.

Btw you are using =- twice in your code while the questions asks for += vs =+. += is a compound operator as well.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading