ตัวดำเนินการเพิ่มจะใช้เพื่อเพิ่มค่าหนึ่งในขณะที่การลดทำงานตรงกันข้ามการเพิ่มขึ้น ตัวดำเนินการลดจะลดค่าลงหนึ่งค่า
เพิ่มล่วงหน้า (++i) − ก่อนกำหนดค่าให้กับตัวแปร ค่าจะเพิ่มขึ้นหนึ่งค่า
หลังเพิ่มขึ้น (i++) − หลังจากกำหนดค่าให้กับตัวแปรแล้ว ค่าจะเพิ่มขึ้น
ต่อไปนี้เป็นไวยากรณ์ของการเพิ่มก่อนและหลัง.
++variable_name; // Pre-increment variable_name++; // Post-increment
ที่นี่
variable_name − ชื่อของตัวแปรที่ผู้ใช้กำหนด
นี่คือตัวอย่างการเพิ่มก่อนและหลังใน C++
ตัวอย่าง
#include <iostream>
using namespace std;
int main() {
int i = 5;
cout << "The pre-incremented value: " << i;
while(++i < 10 )
cout<<"\t"<<i;
cout << "\nThe post-incremented value: " << i;
while(i++ < 15 )
cout<<"\t"<<i;
return 0;
} ผลลัพธ์
The pre-incremented value: 5 6 789 The post-incremented value: 10 1112131415