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

C/C++ Preprocessor Directives


ใน C หรือ C++ เราพบบรรทัดต่างๆ เริ่มต้นด้วยสัญลักษณ์ (#) เรียกว่า preprocessing directives บรรทัดเหล่านี้ถูกประมวลผลในขั้นตอนก่อนคอมไพล์ที่นี่เราจะเห็นสามประเภทของ preprocessing directives:

  • Conditional Compilation
  • Line control
  • Error Directive

บางครั้งเรากำหนด macro ในโปรแกรม ใช้ conditional compilation directives สามารถตรวจสอบว่า macro ถูกกำหนดหรือไม่ เราสามารถควบคุมได้ ดังนั้นถ้า macro หนึ่งถูกกำหนด ทำงานบางอย่าง มิฉะนั้นทำอย่างอื่น

Conditional compilation directives เป็น #ifdef-#elif-#else-#endif ทุกบล็อก #ifdef ต้องจบด้วย #endif #elif หรือ #else เป็นตัวเลือก

ตัวอย่าง

#include 
#define MY_MACRO 10
using namespace std;
int main() {
    #ifdef MACRO
    cout << "MACRO is defined" << endl;
    #elif MY_MACRO
    cout << "MY_MACRO is defined, value is: " << MY_MACRO;
    #endif
}

ผลลัพธ์

MY_MACRO is defined, value is: 10

Line control directive ใช้โดยพิมพ์ #line บางครั้งเราได้ error พร้อมหมายเลขบรรทัดที่ต้องการ เราสามารถอัปเดตหมายเลขบรรทัดได้ด้วย directive นี้ ถ้าเราวางนี้และเปลี่ยนบรรทัดปัจจุบันเป็น 200 บรรทัดถัดไปจะเริ่มจาก 201

ตัวอย่าง

#include 
using namespace std;
int main() {
    cout<< "Current line is: " << __LINE__ << endl;
    #line 200
    cout << "Hello" << endl;
    cout << "World" << endl;
    cout<< "Current line is: " << __LINE__ << endl;
}

ผลลัพธ์

Current line is: 5
Hello
World
Current line is: 202

Error directive ใช้แสดง error ก่อนคอมไพล์ สมมติ macro หนึ่งควรถูกกำหนด แต่ถ้าไม่ได้กำหนด เราสามารถแสดงข้อความ error ได้ ใช้ #error

ตัวอย่าง

#include 
using namespace std;
int main() {
    #ifdef MY_MACRO
    cout << "MY_MACRO is defined, value is: " << MY_MACRO;
    #else
    #error MY_MACRO should be defined
    #endif
}

ผลลัพธ์

#error MY_MACRO should be defined