Quick links: HR Interview Que. Code Snippets C Programs C++ Programs Java Programs Scala Solved Examples PHP Examples

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


Sponsored Links

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

Keywords (like Linux, Java, Oracle etc) used in this website are the trademarks of their respective owners/company. This website is not affiliated to any company. The tutorials are designed by includehelp Team with the help of well known books and other online resources. These Tutorials are free for all, for learning purposes only. Enjoy learning:)
Copyright © 2015 - 2016. All Rights Reserved.