Erlang – Macros

Erlang macros

In this guide, we will discuss Erlang Macros. Macros are generally used for inline code replacements. In Erlang, macros are defined via the following statements.

  • -define(Constant, Replacement).
  • -define(Func(Var1, Var2,.., Var), Replacement).

Following is an example of macros using the first syntax โˆ’

Example

-module(helloworld). 
-export([start/0]). 
-define(a,1). 

start() -> 
   io:fwrite("~w",[?a]).

From the above program you can see that the macro gets expanded by using the โ€˜?โ€™ symbol. The constant gets replaced in place by the value defined in the macro.

The output of the above program will be โˆ’

Output

1

An example of a macro using the function class is as follows โˆ’

Example

-module(helloworld). 
-export([start/0]). 
-define(macro1(X,Y),{X+Y}). 

start() ->
   io:fwrite("~w",[?macro1(1,2)]).

The output of the above program will be โˆ’

Output

{3}

The following additional statements are available for macros โˆ’

  • undef(Macro) โˆ’ Undefines the macro; after this you cannot call the macro.
  • ifdef(Macro) โˆ’ Evaluates the following lines only if the Macro has been defined.
  • ifndef(Macro) โˆ’ Evaluates the following lines only if Macro is undefined.
  • else โˆ’ Allowed after an ifdef or ifndef statement. If the condition was false, the statements following else are evaluated.
  • endif โˆ’ Marks the end of an ifdef or ifndef statement.

When using the above statements, it should be used in the proper way as shown in the following program.

-ifdef(<FlagName>).

-define(...).
-else.
-define(...).
-endif.

Next Topic : Click Here

This Post Has One Comment

Leave a Reply