Macros in C

 

Macros  in C Language:

 On this page we will discuss about macros in c language and its types.Macro is a preprocessor which comes under #define directive.Macro is small part of code which replaces the variable of macro to the value of macro where that macro is used in the program.Macro is very helpful when user wants to change the value of value of a variable at multiple positions.There are different type of macros.

macros in c

Macros in C and Types of Macros

Macro is segment of code or in simple words a small part of code which replaces the name of macro to the value of macro.Macros are defined by the #define directive.It is a preprocessor. Preprocessor is software program that processes the source file prior to sending it to actual compilation.

Syntax:

#define macro_name macro_value

 

Types of Macros

  • Object-Like Macros
  • Function-Like Macros

Object-Like Macros in C:

Its is widely used to represent numeric constant.Basic synatx of object-like macro is “#define a 10 “.Where #define is a preprocessor directive a is macro name and 10 is macro value.

Programming example of object-like macro:

Run
#include <stdio.h>
#define DATE 25	  // Object-Like Macro
int main ()
{

  printf ("Christmas is celebrated world wide on %d-DEC", DATE);

  return 0;
}

Output:

Christmas is celebrated world wide on 25-DEC

Function-Like Macros in C:

Its replaces the value of macro name with macro function.It looks like a function call.It substitute the entire code in place of function name.

For Example: #define min(a,b) (((a)< (b)) ? (a) : (b) ).Here min(a,b) is function name which replaces with the code given everywhere in the program.

Programming example of  Function-like macro:

Run
#include<stdio.h> 

//object like macro
#define PI 3.14

// function like macro
#define Ar(r) (PI*(r*r))

void main ()
{

  float rad = 4.5;
  float area = Ar (rad);

  printf ("Area of circle is %f\n", area);

  int radInt = 7;
  printf ("Area of circle is %f", Ar (radInt));


}

Output:

Memory is created successfully 
Area of circle is 63.584999
Area of circle is 153.860000

Predefined Macros

Here some of the macros which are predefined in C language.

MacroValue
__DATE__A string containing the current date.
__FILE__A string containing the file name.
__LINE__An integer representing the current line number.
__STDC__If follows ANSI standard C, then the value is a nonzero integer.
__TIME__A string containing the current time.

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription