Monday 21 March 2016

Julia: const: Declare constants


‘const’ keyword is used to declare constants. If you try to assign a new value of same type to the constant variable, you will get a warning, but new value reflects.
julia> const sal=12345.6
12345.6

julia> sal
12345.6

julia> sal=54321.6
WARNING: redefining constant sal
54321.6

julia> sal
54321.6


When you try to redefine constant variable with new value of different type, you will get an error and new value will not reflect.
julia> typeof(sal)
Float64

julia> sal
54321.6

julia> sal="hello"
ERROR: invalid redefinition of constant sal

julia> sal
54321.6


If you use const for a mutable type like array, you can change the contents of the the array, but you can’t change it to a different array.
julia> const arr1=[2, 3, 5]
3-element Array{Int64,1}:
 2
 3
 5

julia> arr1[1]=7
7

julia> arr1
3-element Array{Int64,1}:
 7
 3
 5

julia> arr2=[2, 4, 6]
3-element Array{Int64,1}:
 2
 4
 6

julia> arr1=arr2
WARNING: redefining constant arr1
3-element Array{Int64,1}:
 2
 4
 6

julia> arr1
3-element Array{Int64,1}:
 2
 4
 6

julia> arr1="Hello"
ERROR: invalid redefinition of constant arr1

julia> arr1
3-element Array{Int64,1}:
 2
 4
 6



Previous                                                 Next                                                 Home

No comments:

Post a Comment