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

พิมพ์ Hello World โดยไม่ใช้ Semicolon ใน C++


บทนำ

มีหลายวิธีเขียนโปรแกรม C++ โดยไม่ใช้ semicolon (;) แต่ นี่เป็น bad practice และไม่ควรนำไปใช้ในโค้ดจริง เนื้อหานี้เพื่อการศึกษาเท่านั้น

วิธีที่ง่ายที่สุด: ใช้ if statement

เกือบทุกคำสั่งใน C++ สามารถจัดเป็น expression ได้ หากวางคำสั่งภายใน if statement พร้อมวงเล็บว่าง จะไม่ต้องจบด้วย semicolon

ตัวอย่างที่ 1: พิมพ์ Hello World

#include <iostream>
int main() {
    if (std::cout << "Hello world!") {}
}

ผลลัพธ์

Hello World

ตัวอย่างที่ 2: รับค่าและแสดงผล

#include <iostream>
int main() {
    if (int N = 1) {
        if (std::cin >> N) {}
        if (std::cout << N) {}
    }
}

ผลลัพธ์ (กรอก 21)

21

การหลีกเลี่ยงคำสั่งอื่นๆ

  • break, continue: ใช้เงื่อนไขในลูปแทน
  • goto: จัดโครงสร้าง control flow ให้ดีกว่า
  • return (non-void): ใช้ reference parameter แทนค่าส่งคืน