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

คำสั่ง Goto ใน C/C++

คำสั่ง goto เป็นคำสั่งกระโดด (jump statement) ใช้กระโดดจากจุดหนึ่งไปยังอีกจุดหนึ่งในฟังก์ชันเดียวกัน ไม่แนะนำให้ใช้ เพราะทำให้โค้ดซับซ้อน ยากต่อการติดตามและแก้ไข

รูปแบบไวยากรณ์

goto label;
...
label: statement;

ตัวอย่าง

#include <stdio.h>
int main() {
    int a = 10;
    LOOP:
    do {
        if (a == 12) {
            a = a + 1;
            goto LOOP;
        }
        printf("Value of a: %d\n", a);
        a++;
    } while (a < 15);
    return 0;
}

ผลลัพธ์

Value of a: 10
value of a: 11
value of a: 13
value of a: 14