# Should I add a semicolon after a function definition? [duplicate]

should I write the program like this:

f[x_]:=x^2;
g[x_]:=x+2;


or should I write the program like this:

f[x_]:=x^2
g[x_]:=x+2


Which one is good practice, does any of them have side effect?

• No difference that I know, except that you can put multiple pieces of code on one line, when they are separated by semicolons. – bbgodfrey Jul 10 '16 at 1:32
• One trivial side effect is that a semicolon affects indentation in the front end. – Michael E2 Jul 10 '16 at 2:32

There is a difference between SetDelayed (:=) with or without semicolon, but it usually doesn't matter. The semicolon is actually a CompoundExpression which has Null as its last element - that's the one that gets returned.

But SetDelayed returns Null, too. So the results returned with or without semicolon are the same.

An exception to this statement occurs when the SetDelayed fails, as in the case 2:=1 where I try to assign a value in a forbidden way. Then SetDelayed returns $Failed instead of Null. But if you end the := assignment with a semicolon, then the result $Failed is not returned, because the Null is still the last expression in CompoundExpression. Therefore, if you're doing := inside a structure that watches for the occurrence of \$Failed in the assignment, you can't use the semicolon. Here is a test:

Print[2 := 1];
Print[2 := 1;]


In normal usage in the notebook, I don't think there's any reason to use the semicolon after :=. However, one more case where I find it safer to use semicolons at the ends of such lines is when the code is not in a notebook but in a text file that may be read on different platforms, where line breaks could potentially be gobbled up so that the semicolon is a safety measure, preventing lines from unintentionally being merged into one.

• Jens, I have marked this question as a duplicate. Please let me know if you disagree. – Mr.Wizard Jul 10 '16 at 11:59
• @Mr.Wizard You're right, I think you covered everything there, and even mentioned SetDelayed. I must have overlooked that thread. – Jens Jul 10 '16 at 15:40
• Someone is using M11... ;-) – P. Fonseca Jul 12 '16 at 12:02
• @P.Fonseca Yes, don't you love the stylish messages? – Jens Jul 12 '16 at 14:58