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

รัน if และ else พร้อมกันใน C/C++


ในส่วนนี้เราจะดูวิธี execute if และ else พร้อมกันในโค้ด C หรือ C++ วิธีนี้ค่อนข้าง tricky

เมื่อ if และ else ทำงานทีละอัน มันเหมือน execute statements ที่ไม่มี if-else แต่ที่นี่เราจะดูว่า ถ้ามี if-else อยู่ จะทำให้รันทีละบล็อกได้อย่างไร

ตัวอย่างโค้ด

#include <iostream> using namespace std; int main() {    int x = 10;    if(x > 5)   {       lebel_1: cout << "This is inside if statement" <<endl;       goto lebel_2;    }else{       lebel_2: cout << "This is inside else statement" <<endl;       goto lebel_1;    } }

ผลลัพธ์

This is inside if statement This is inside else statement This is inside if statement This is inside else statement This is inside if statement This is inside else statement This is inside if statement This is inside else statement .... .... ....

โปรแกรมนี้ทำงานเป็น infinite loop แต่ if block และ else block execute พร้อมกัน หลังตรวจสอบเงื่อนไขครั้งแรก การตรวจสอบเงื่อนไขไม่ส่งผลต่อ output อีกต่อไป

หมายเหตุ: ใช้ goto บังคับให้ control ไปจาก if ไป else และ else ไป if แต่การใช้ goto ไม่ดี เพราะทำให้ยากต่อการ trace control flow