Variable definition like C++

Hello,
In the C++ programming language, the definition of a variable is as follows:

int res = 1;

How is this done in Julia?

Thank you.

In Julia, you just set the value to something.

So, in this case…

res = 1

Hi,
How about:

a = Int(1)

s = String("Hello")

Are these wrong?

They work, but they’re redundant.

1 Like

Minor addition: int in C/C++ corresponds to Int32 in Julia. So, technically, you could write res = Int32(1) to get the same value as in your C++ example. However, unless you really care about the difference between Int32 and Int64 (the default in Julia), you shouldn’t care about this.

2 Likes

You can alternatively specify the type as part of the assignment:

a::Int64 = 1

I hesitate to mention this, though, because it has different semantics to normal variable assignment and is rarely used. In this case the variable a cannot be reassigned a different type later on: all assignments to a will attempt a (safe) conversion or else will throw an error.

I would recommend not to use this form unless you know why you need it (perhaps, for example, for type stability reasons).

In any case, the documentation for assignments is here: Types · The Julia Language

2 Likes

I’m not completely sure about String, but in general it’s not a good idea to explicitly call a constructor on something that’s already of the same type, as you risk creating the value twice, needlessly.

2 Likes

Seconding @DNF. These do work but they are wrong because Typename(object) by convention returns a freshly created object (Conversion and Promotion · The Julia Language). It does not matter for isbits types but it causes copying for containers (e.g., Vector([1, 2, 3]) would create two copies of the array immediately discarding one of them).

If you want to ensure the variable type, use

a::Int = 1

or

a = 1::Int

The first fixes the type of the variable, so that if rhp is of different type, then it’s converted to a given type before writing into a.
The second asserts the type of rhp, so that if it’s of a different type, you’ll get AssertionError.

In practice, I’d prefer the former, but for self-teaching you may want to try the latter to see which types to expect from different expressions and build some understanding of the type system.

1 Like

(post deleted by author)