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

โครงสร้างโปรแกรม C++ (C++ Program Structure)


โปรแกรม Hello World

#include <iostream>
int main() {
    std::cout << "Hello World\n";
}

วิเคราะห์โปรแกรมทีละบรรทัด

บรรทัด 1: #include <iostream>

บอกคอมไพเลอร์ให้ copy โค้ดจากไฟล์ iostream (จัดการ input/output streams) มาใน source file เริ่มด้วย # เป็น preprocessor directive

บรรทัด 2: บรรทัดว่าง

ไม่มีผลต่อโปรแกรม ใช้เพื่อ readability

บรรทัด 3: int main() {

ประกาศฟังก์ชัน main ที่เป็น entry point ของโปรแกรม ทุกโปรแกรม C++ เริ่มทำงานที่ main() วงเล็บ { เริ่มต้น function body

บรรทัด 4: std::cout << "Hello World\n";

คำสั่ง C++ ที่มี 3 ส่วน:

  1. std::cout - standard console output device
  2. << - insertion operator ใส่ข้อมูลเข้า cout
  3. "Hello World\n" - สตริงที่ต้องการพิมพ์ (\n = newline)
จบด้วย semicolon (;) บ่งชี้จบ statement

บรรทัด 5: }

ปิด function body ของ main()

สรุป

โปรแกรม C++ ขั้นพื้นฐานประกอบด้วย: preprocessor directive, main function, statements ภายใน block { } และ semicolon ท้ายแต่ละ statement