Macro

้เป็นคำสั่งที่ใช้ในการกำหนดค่า ประเภท หรือฟังก์ชัน โดยจะทำในกระบวนการ Preprocessing ทำไมถึงไม่ทำในโปรแกรมไปเลยทำไม่ต้องทำให้ยุ่งยาก งั้นมาดูกันครับว่าทำไมต้องใช้

Macro

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

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

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

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

Example C++

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

Example 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

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

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

Output

0
1
2
3
4

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

Example C++

#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

#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

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

	area = l1 * l2;

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

	return 0;
}

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

Output

Area of rectangle is: 50

Last updated

Assoc. Prof. Wiroon Sriborrirux, Founder of Advance Innovation Center (AIC) and Bangsaen Design House (BDH), Electrical Engineering Department, Faculty of Engineering, Burapha University