should I write the program like this:


or should I write the program like this:


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

  • $\begingroup$ No difference that I know, except that you can put multiple pieces of code on one line, when they are separated by semicolons. $\endgroup$
    – bbgodfrey
    Jul 10 '16 at 1:32
  • 1
    $\begingroup$ One trivial side effect is that a semicolon affects indentation in the front end. $\endgroup$
    – 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.

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.