Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

Pre-increment และ Post-increment ใน C/C++

Pre-increment (++x) เพิ่มค่าก่อน แล้วคืนค่าใหม่ Post-increment (x++) คืนค่าเก่าก่อน แล้วค่อยเพิ่ม

ตัวอย่าง

#include <iostream>
using namespace std;

int main() {
    int x = 10, y = 10, z;
    z = ++x;  // z = 11, x = 11
    cout << "Z: " << z << endl;
    z = y++;  // z = 10, y = 11
    cout << "Z: " << z << " and y is: " << y << endl;
    return 0;
}

ผลลัพธ์

Z: 11
Z: 10 and y is: 11

Precedence ของ Post-increment สูงกว่า Pre-increment และ Associativity ต่างกัน (Pre: Right-to-Left, Post: Left-to-Right)