”;
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.
”;