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

Multiline Macros ในภาษา C

เขียน Macro หลายบรรทัด ต้องทุกบรรทัดด้วย Backslash (\) และควรห่อด้วย Parentheses ป้องกันข้อผิดพลาด

ตัวอย่าง

#include <stdio.h>

#define PRINT(x, str) ({ \
    printf("The number %d", x); \
    printf(" is "); \
    printf(#str); \
    printf("\n"); \
})

int main() {
    int x = 10;
    if (x % 2 == 0) {
        PRINT(x, EVEN);
    }
    return 0;
}

ผลลัพธ์

The number 10 is EVEN