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

Pre-increment และ Pre-decrement ในภาษา C

ตัวดำเนินการเพิ่ม (++) เพิ่มค่าขึ้น 1 ตัวดำเนินการลด (--) ลดค่าลง 1

รูปแบบ Pre-increment

++variable_name;

รูปแบบ Pre-decrement

--variable_name;

Pre-increment

เพิ่มค่าก่อนแล้วค่อยนำค่าไปใช้

ตัวอย่าง

#include <stdio.h>
int main() {
    int i = 5;
    printf("The pre-incremented value : %d\n", i);
    while (++i < 10)
        printf("%d\t", i);
    return 0;
}

ผลลัพธ์

The pre-incremented value : 5
6 7 8 9

Pre-decrement

ลดค่าก่อนแล้วค่อยนำค่าไปใช้

ตัวอย่าง

#include <stdio.h>
int main() {
    int i = 10;
    printf("The pre-decremented value : %d\n", i);
    while (--i > 5)
        printf("%d\t", i);
    return 0;
}

ผลลัพธ์

The pre-decremented value : 10
9 8 7 6