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!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.