When and where should we use semicolon

Problem

This might be a somehow uninteresting question. But when I read other people’s code snippets, I find that the use of semicolon does not follow certain patterns and seems to be a little random for me.

I know semicolon is used to suppress output just like in MATLAB. When I write code in MATLAB, I generally add semicolons everywhere like writing C/C++/Java. When output is needed, I just use print function to get what I want. I am not sure whether this is still preferable in Julia. If it is the case and it doe not fall into something people need to avoid, it would be good for consistency across different code snippets.

I generally omit the semicolon and that seems to be the norm. The semicolons you find in code snippets might be to suppress output when the code is pasted into the REPL.

3 Likes

I was expecting to see advice for semicolon in the style guide but, I don’t. Semicolons helpful for single-line responses in chat sessions that you can copy/paste; and they are used for suppressing output in some tools. Otherwise they don’t seem to be used much.

I’m not an expert but I never add semicolons since I develop code iteratively running chunks of my code all the time to see the output. But I’m not sure what other people do. Therefore I would argue against using them. Nothing is printed when running it as a script anyway.

It’s very rare to see trailing semicolons in most Julia code. I guess in the context of a README or something where you’re expecting someone to copy-paste a particular line and want to suppress output, but I definitely wouldn’t add semicolons as a habit.

Not only that: it can act as a separator between expressions:

julia> (a = 1; b = 2; c = a+b; c)
3

and syntax for hcat:

[1 2;
 3 4]

Suppressing output is primarily for interactive use, it is rarely ever seen it in code, because in idiomatic Julia, most code is inside functions. The exception could be a script which produces results that print something large and unnecessary.

8 Likes