Search code examples
syntaxerlang

Erlang: What does question mark syntax mean?


What does the question mark in Erlang syntax mean?

For example:

Json = ?record_to_json(artist, Artist).

The full context of the source can be found here.


Solution

  • Erlang uses question mark to identify macros. For e.g. consider the below code:

    -ifdef(debug).
    -define(DEBUG(Format, Args), io:format(Format, Args)).
    -else.
    -define(DEBUG(Format, Args), void).
    -endif.
    

    As the documentation says,

    Macros are expanded during compilation. A simple macro ?Const will be replaced with Replacement.

    This snippet defines a macro called DEBUG that is replaced with a call to print a string if debug is set at compile time. The macro is then used in the following code thus:

    ?DEBUG("Creating ~p for N = ~p~n", [First, N]),
    

    This statement is expanded and replaced with the appropriate contents if debug is set. Therefore you get to see debug messages only if debug is set.

    Update

    Thanks to @rvirding:

    A question mark means to try and expand what follows as a macro call. There is nothing prohibiting using the macro name (atom or variable) as a normal atom or variable. So in [the above] example you could use DEBUG as a normal variable just as long as you don't prefix it with ?. Confusing, most definitely, but not illegal.