Home » C programming language

Macro expansion directives (#define, #undef) in C language

Here, we will learn about c programming macros, how to define and un define a macro, how and when macro expands?

What is Macro?

Macros are the names of text/ literal values/ string (constant values) or code fragment, which will expand when pre-processor processes the macro.

Pre-processor processes the macros at compile time; hence that macros replace with the corresponding code fragments.

There are basically two pre-processor Macro Expansion directives: #define and #undef

1) #define - defining a macro

#define creates/define a macro.

Defining a simple macro

A macro definition has following form:

#define macro_name code_fragment

Here,

  • #define is a pre-processor directive
  • macro_name is the name of macro
  • code_fragment is the statement which is compiled at the place of the macro

Consider this example

Here we are defining three macros NAME, PI and MAXBUFF with some constant values

#include<stdio.h>
 
#define NAME    "includhelp.com"
#define PI      3.14
#define MAXBUFF 100
 
int main()
{
    printf("\nNAME : %s",NAME);
    printf("\nPI : %f",PI);
    printf("\nMAXBUFF : %d",MAXBUFF);
    return 0;
}

Output

NAME : includhelp.com
PI : 3.140000
MAXBUFF : 100

How to define a complex macro with argument (function like macros)?

Read: Complex macro with arguments (function like macro) in C language.

2) #undef - Un defining a defined macro

#unndef directive is used to un define a defined macro in source code, macro must be defined if you are trying to un defining a macro.

#undef has following form:

#undef defined_macro_name

Consider the example

Here, we are defining a macro MAXBUF, then un defining and redefining macro with new value.

/* program define, undefine and redefine a macro*/
#include<stdio.h>
 
int main()
{
    /*Define MAXBUFF*/
    #define MAXBUFF 100
    printf("\nMAXBUFF is : %d",MAXBUFF);
 
    #undef  MAXBUFF         /*Un-define MAXBUFF*/
    #define MAXBUFF 200     /*Redefine MAXBUFF*/
 
    printf("\nMAXBUFF is : %d",MAXBUFF);
    return 0;
}

Output

MAXBUFF is : 100
MAXBUFF is : 200





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL







Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.