การแทนที่มาโครเป็นกลไกที่จัดให้มีการแทนที่สตริง สามารถทำได้โดย " #deifne" .
ใช้เพื่อแทนที่ส่วนแรกด้วยส่วนที่สองของคำจำกัดความมาโคร ก่อนการทำงานของโปรแกรม
วัตถุแรกอาจเป็นประเภทฟังก์ชันหรือวัตถุ
ไวยากรณ์
ไวยากรณ์สำหรับมาโครมีดังนี้ −
#define first_part second_part
โปรแกรม
ในโปรแกรมสำหรับทุกๆ first_part จะถูกแทนที่ด้วย second_part ตลอดทั้งโค้ด
#include<stdio.h>
#define square(a) a*a
int main(){
int b,c;
printf("enter b element:");
scanf("%d",&b);
c=square(b);//replaces c=b*b before execution of program
printf("%d",c);
return 0;
} ผลลัพธ์
คุณจะเห็นผลลัพธ์ต่อไปนี้ -
enter b element:4 16
พิจารณาโปรแกรมอื่นที่อธิบายการทำงานของมาโคร
#include<stdio.h>
#define equation (a*b)+c
int main(){
int a,b,c,d;
printf("enter a,b,c elements:");
scanf("%d %d %d",&a,&b,&c);
d=equation;//replaces d=(a*b)+c before execution of program
printf("%d",d);
return 0;
} ผลลัพธ์
คุณจะเห็นผลลัพธ์ต่อไปนี้ -
enter a,b,c elements: 4 7 9 37