Function vs macro

I saw codes like

@warn("the number of particles must be positive")


@show    a,  b,  c 

Becaue of the @, both are macros, right? The first contains the (), which makes it closer to a function; the second contains even no (), so looks very casual.

What is similarity and difference between functions and macros?

1 Like

There are two ways of calling a macro. Here is the relevant section of the manual.

Functions and macros serve to build abstractions on totally different levels. At the highest level a function captures some behavior of the program, while a macro captures some behavior of the code of the program. That is if your program has to do something repeatedly you use a function. If your code looks repetitive, then you can use a macro to abstract that repetition away. I recommend reading a bit through the manual page I linked above to learn more about metaprogramming and macros in Julia.
A general word of warning though: Never use a macro, if an ordinary function can achieve similar results.


Functions receive values as parameters, are evaluated at runtime, and return a value to the surrounding expression.

Macros receive source code (abstract-syntax-tree expressions) as arguments, are evaluated at compile time, and return source code to the compiler, which will then compile it.

For example, the macro @show a knows the name of the variable it received, and therefore can output a = 5, whereas the function show(a) knowns only the value of variable a, not its name, and therefore can only output 5.