Home > Backend Development > C++ > What are macros in C programming language?

What are macros in C programming language?

PHPz
Release: 2023-09-05 11:29:06
forward
842 people have browsed it

What are macros in C programming language?

Macro substitution is a mechanism that provides string replacement. It can be achieved by "##define".

It is used to replace the first part of the macro definition with the second part before the program is executed.

The first object can be a function type or an object.

Syntax

The syntax of the macro is as follows:

#define first_part second_part
Copy after login

Program

In the program, every time first_part appears, it will be replaced by second_part.

Online Demo

#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;
}
Copy after login

Output

You will see the following output −

enter b element:4
16
Copy after login

Consider another program that interprets macro functions.

Live Demo

#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;
}
Copy after login

Output

You will see the following output −

enter a,b,c elements: 4 7 9
37
Copy after login

The above is the detailed content of What are macros in C programming language?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template