Question about the diffrence between a + 2; and a += 2;

Hello,

In the Unreal C++ course, the video about Pre vs Post Increment / Decrement in the Bull Cow Game section Mike uses d = a += 2; at 6:20, but I’m wondering why he uses += instead of just +. I’ve tried both but I seem to get the same results so I wanted to know if there is a difference and if there is when you should use += instead of just +.

Thanks in advance,
Matis

There is a difference, a += b is the same as a = a + b, therefor this line

d = a += 2;

modifies a.

int a = 1;
int b = a += 2;
std::cout << a << ' ' << b << '\n'; // prints 3 3

Whereas

int a = 1;
int b = a + 2;
std::cout << a << ' ' << b << '\n'; // prints 1 3

Live demo: Compiler Explorer

Thank you for clearing things up!

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms