In a loop in C++, I usually encounter situations to use ++
or +=1
, but I can't tell their difference. For instance, if I have an integer
int num = 0;
and then in a loop I do:
num ++;
or
num += 1;
they both increase the value of num
, but what is their difference? I doubt num++
could work faster than num+=1
, but how? Is this difference subtle enough to be ignored?
num += 1
is rather equivalent to ++num
.
All those expressions (num += 1
, num++
and ++num
) increment the value of num
by one, but the value of num++
is the value num
had before it got incremented.
Illustration:
int a = 0;
int b = a++; // now b == 0 and a == 1
int c = ++a; // now c == 2 and a == 2
int d = (a += 1); // now d == 3 and a == 3
Use whatever pleases you. I prefer ++num
to num += 1
because it is shorter.