C language basics: a++ and ++a
- 2020-05-30 20:50:52
- OfStack
(1) a + +
In C or other languages, the ++ sign means "self-addition", which means adding 1 to the original variable.
Case 1:
a = 0;
a++;
Then the value of a is 1.
By the same token, it means "self-subtracting".
Example 2:
a = 100;
a--;
Then the value of a is 99.
Note that there is no such thing as "self multiplication" or "self division" in programming languages.
Verification procedure:
#include <stdio.h>
int main()
{
int a = 0; // to a The assignment
a++;
printf("After ++, a = %d\n", a);
a = 100; // Back to the a The assignment
a--;
printf("After --, a = %d\n", a);
return 0;
}
Operation results:
After ++, a = 1
After --, a = 99
(2) + + a
In addition to a++ for self-addition, ++a also means self-addition. Same idea --a for self-subtraction
Verification procedure:
#include <stdio.h>
int main()
{
int a = 0; // to a The assignment
++a;
printf("After ++, a = %d\n", a);
a = 100; // Back to the a The assignment
--a;
printf("After --, a = %d\n", a);
return 0;
}
Operation results:
After ++, a = 1
After --, a = 99
(3) differences between a++ and ++a
Since a++ and ++a are both added by a, are the two exactly the same?
Let's look at a program:
#include <stdio.h>
int main()
{
int a = 0;
printf("a = %d\n", a++);
printf("a = %d\n", a);
printf("a = %d\n", ++a);
printf("a = %d\n", a);
return 0;
}
Operation results:
a = 0
a = 1
a = 2
a = 2
As can be seen from the operation results, a++ and ++a are different:
a++ reads the value of a first, then increments the value of a by 1;
++a increments the value of a by 1 before reading the value of a.