# Macro

## Macro

โดยปกติ macro ในภาษา C/C++ เราจะพบได้ในตัวโปรแกรมบางโปรแกรมเช่น Arduino ในการโปรแกรมถ้าผู้เรียนเรียนอยู่ในวิศวกรรมไฟฟ้า หรือวิศวสาขา Embedded System ต้องเคยพบเห็นการทำงานในลักษณะนี้ ผู้เขียนจะยกตัวอย่างให้เห็นภาพดังนี้

```c
#define LED 12; //กำหนด GPIO ขา 12 ชื่อว่า LED
#define LED HIGH; //ให้ GPIO ขา 12 มีค่า 1 หรือ High state 
```

โดยการใช้งาน macro ในการ preprocess จะเปรียบเสมือนการแทนค่าลงไปบนชื่อที่กำหนดก่อนนำไปทำการคอมไพล์เพื่อสะดวกและป้องกันความสับสนหรือความผิดพลาดจากการกรอกตัวเลข หรือกระบวนการทางคณิตศาสตร์

### Macro ทำหน้าที่เป็นค่าคงที่

#### Example C++

```cpp
#include <iostream>
 
// macro definition
#define LIMIT 5
int main()
{
    for (int i = 0; i < LIMIT; i++) {
        std::cout << i << "\n";
    }
 
    return 0;
}
```

#### Example C

```c
#include <stdio.h>
 
// macro definition
#define LIMIT 5
int main()
{
    for (int i = 0; i < LIMIT; i++) {
        printf("%d \n",i);
    }
 
    return 0;
}
```

จากรูปเมือทำการ preprocess เป็นไฟล์ .i จะพบว่าค่าที่กำหนดไว้ไปแทนค่าก่อนทำการคอมไพล์ดังรูป

#### After Preprocessing

```c
int main()
{
    for (int i = 0; i < 5; i++) {
        printf("%d \n",i);
    }
 
    return 0;
}
```

ซึ่งหลังจากทำการคอมไพล์และรันทดสอบจะได้ผลลัพธ์ดังตัวอย่าง

#### Output

```c
0
1
2
3
4
```

### Macro ทำหน้าที่เป็นฟังก์ชัน

#### Example C++

```cpp
#include <iostream>

// macro with parameter
#define AREA(l, b) (l * b)
int main()
{
	int l1 = 10, l2 = 5, area;

	area = AREA(l1, l2);

	std::cout << "Area of rectangle is: " << area;

	return 0;
}

```

#### Example C

```cpp
#include<iostream>
using namespace std;

// macro with parameter
#define AREA(l, b) (l * b)

int main()
{
	int l1 = 10, l2 = 5, area;

	area = AREA(l1, l2);

	cout << "Area of rectangle is: %d \n", area;

	return 0;
}

```

จากรูปเมือทำการ preprocess เป็นไฟล์ .i จะพบว่าค่าที่กำหนดไว้ไปแทนค่าก่อนทำการคอมไพล์ดังรูป

#### After Preprocessing

```c
int main()
{
	int l1 = 10, l2 = 5, area;

	area = l1 * l2;

	cout << "Area of rectangle is: %d \n", area;

	return 0;
}
```

ซึ่งหลังจากทำการคอมไพล์และรันทดสอบจะได้ผลลัพธ์ดังตัวอย่าง

#### Output

```c
Area of rectangle is: 50
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.aic-eec.com/c-c++-for-embedded-programming/c-c++-preprocessing/macro.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
