English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Macros (Macros) in Erlang

Macros are usually used for inline code replacement. In Erlang, macros are defined by the following statement.

  • - define(Constant, Replacement).

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

Here is an example of a macro using the first syntax-

The following is an example of using macro with function class

-Example 
-module(helloworld)./export([start 
-define(a,1) 
start() -> 
   io:fwrite("~w",[?a]).

From the above program, you can see that the macro is extended using '?'. The symbol. Constants will be replaced with the values defined in the macro.

The output of the above program will be-

Output Result

1

as shown-

The following is an example of using macro with function class

-Example 
-module(helloworld)./export([start 
-0]).1define(macro+(X,Y),{X 
start() ->
   io:fwrite("~w",[?macro1(1,2)).

The output of the above program will be-

Output Result

{3}

The following additional statements can be used for macros-

  • undef(Macro)-The macro is not defined; thereafter, you will not be able to call the macro.

  • ifdef(Macro) −The following lines are evaluated only if the macro is defined.

  • ifndef(Macro) −The following lines are evaluated only if the macro is not defined.

  • else−Allowed after ifdef or ifndef statements. If the condition is false, the statements after else are evaluated.

  • endif −Mark the end of the ifdef or ifndef statement.

When using the above statements, they should be used correctly as shown in the following program.

-ifdef(<FlagName>).
-define(...).
-else.
-define(...).
-endif.