Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Directive #define Preprocessor trong C++ là gì?


#define tạo một macro, là sự liên kết giữa một identifier hoặc parameterized identifier với một token string. Sau khi macro được định nghĩa, compiler có thể thay thế token string cho mỗi lần xuất hiện của identifier trong file nguồn.

#define identifier token-string

Đây là cách preprocessor được dùng. Directive #define khiến compiler thay thế token-string cho mỗi lần xuất hiện của identifier trong file nguồn. Identifier chỉ được thay thế khi nó tạo thành một token. Nghĩa là, identifier không bị thay thế nếu nó xuất hiện trong comment, trong string, hoặc như một phần của identifier dài hơn.

Ví dụ

#include 
#define MY_VAR 55
using namespace std;
int main() {
    int x = 10;
    cout << x + MY_VAR;
    // Sau tiền xử lý biểu thức này trở thành: x + 55
    return 0;
}

Kết quả

Đây sẽ cho output:

65

Bạn có thể đọc thêm về directive #define tại MSDN: https://docs.microsoft.com/en-us/cpp/preprocessor/hash-define-directive-c-cpp