Increment (Prefix and Postfix)
C++ provides us with the assignment operators which help to shorten the code and make it more readable. They can assign the value and perform the operation at the same time.
The same syntax can be applied to all operators:
12345x += 2; // is equivalent to x = x + 2 x -= 3; // is equivalent to x = x - 3 x *= 4; // is equivalent to x = x * 4 x /= 2; // is equivalent to x = x / 2 x %= 5; // is equivalent to x = x % 5
The increment operator ++
and decrement operator --
increases and decreases the value of the variable by 1 respectively:
1234int x = 2; int y = 2; cout << ++x << endl; cout << --y;
The operator ++
has two forms: prefix (++x) and postfix (x++).
- Prefix increments/decrements firstly the value and then evaluates the expression.
- Postfix evaluates firstly the expression and then increments/decrements the value.
Example:
1234int x = 2; int y = 2; cout << "x: " << x++ << endl; // Firstly print the value and then increase it by 1 cout << "y: " << ++y << endl; // Firstly increase the value by 1 and then print it
Takk for tilbakemeldingene dine!
Spør AI
Spør AI
Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår
Awesome!
Completion rate improved to 3.33
Increment (Prefix and Postfix)
Sveip for å vise menyen
C++ provides us with the assignment operators which help to shorten the code and make it more readable. They can assign the value and perform the operation at the same time.
The same syntax can be applied to all operators:
12345x += 2; // is equivalent to x = x + 2 x -= 3; // is equivalent to x = x - 3 x *= 4; // is equivalent to x = x * 4 x /= 2; // is equivalent to x = x / 2 x %= 5; // is equivalent to x = x % 5
The increment operator ++
and decrement operator --
increases and decreases the value of the variable by 1 respectively:
1234int x = 2; int y = 2; cout << ++x << endl; cout << --y;
The operator ++
has two forms: prefix (++x) and postfix (x++).
- Prefix increments/decrements firstly the value and then evaluates the expression.
- Postfix evaluates firstly the expression and then increments/decrements the value.
Example:
1234int x = 2; int y = 2; cout << "x: " << x++ << endl; // Firstly print the value and then increase it by 1 cout << "y: " << ++y << endl; // Firstly increase the value by 1 and then print it
Takk for tilbakemeldingene dine!