In C++, I can declare my variables in one line like:
int x, y, z;
In Julia, it seems that I have to declare their types one by one,
x :: Int64
y :: Int64
z :: Int64
Can I do this at once?
In C++, I can declare my variables in one line like:
int x, y, z;
In Julia, it seems that I have to declare their types one by one,
x :: Int64
y :: Int64
z :: Int64
Can I do this at once?
Is it important to have it only in one line or repeat the type only once? For the former:
x::Int64; y::Int64; z::Int64
The latter one
Consider in C all of the confusion caused by: char *src = 0, c = 0;
and int i, j = 1;
I have a funny feeling the C++ committee would have removed that feature if they could.
You could write a macro @deftype Int x y z
This is not something that you need to do in Julia. What is the use case?
I am used to the C++ and Fortran coding style, and just want to know if I can do this in Julia.
Hi @Yifan_Liu,
Keep in mind @jlperla’s comment on the unclear expressions that you can write in C++. You may be saving yourself a few key strokes today, but whoever needs to read your code in the future will waste time, including yourself.
Also, as @dpsanders mentioned, Julia takes care of the types for you, you don’t need to be explicit about it. Let the language figure it out.
From time to time, I feel like that in Julia if I code like C++/ Fortran style my code will run faster, if I code like python style my code will run slower.
Is it my illusion or something that makes a little bit sense… I do not know
By adding the types you are helping the compiler to not make mistakes, I guess. But in general this gap in performance that you see should go away with future releases of the language? I am not the most qualified person to answer your question, but I do agree that sometimes you need to go a little more explicit to get an extra power.
What happens sometimes is that you end up overwriting variables like in:
a = 1
a = a + 1. # oops, changed from Int to Float64
and this compromises performance. When you are explicit about the types, I think you can’t make these mistakes easily. The good news is that you are still writing the same language, you don’t need to resort to another compiler to off-load the computation. Start without type annotation and add explicit types if you really need it.
It’s very very rare that you need to be explicit with types, and in any case that happens I think there’s a bug report open for it. But in most cases that users of Julia will rub into (except maybe the closure bug), adding type information will not help the compiler make things faster if the variables are not global.
Adding type declarations for safety is a different thing, but you could also just use @code_warntype
and fix any instabilities at the root of the issue.