Search code examples
cprogramming-languages

a++ vs a = a + 1 which is useful in efficient memory programming and how?


This was my Interview question in HP. I answered a++ takes less instruction compared to a = a +1;

I want to know which is useful in efficient programming, and how both are different from each other..?

Hoping for quick and positive response..


Solution

  • In C, there would be no difference, if the compiler is smart.

    In C++, it depends on what type a is, and whether the ++ operator is overloaded. To complicate matters even more, the = operator can be overloaded too, and a = a + 1 might not be the same as a++. For even more complication, the + operator can also be overloaded, so an innocent looking piece of code such as a = a + 1 might have drastic implications.

    So, without some context, you simply cannot know.