Defining constant global Variables in Julia
Asked Answered
F

2

5

In Julia, what is difference between defining a variable as const and defining a variable as const global? Considering the following example, what is the difference if I change const global to const?

#set number of cores
number_cores=7;
addprocs(number_cores)

#include necessary functions
@everywhere include("$(pwd())\\lib.jl");

const global n = 2; # number of observables
const global k = nVAR + 2*n-1; # number of states
const global m = k*q;

pmap(a->parallel_un(a,n,k,m),1:7)
Frodeen answered 14/2, 2018 at 7:4 Comment(2)
as a side comment - why do you use @sync @async before pmap? I think it should have no effect?Tirza
You are right, @sync @async is not necessary in this case.Frodeen
K
9

There are two cases:

  1. If you are in the global scope then const and const global are the same;
  2. If you are in some scope other than global then using const is deprecated in Julia 0.7 and using const global is acceptable and defines a global constant.

Here is an example session:

               _
   _       _ _(_)_     |  A fresh approach to technical computing
  (_)     | (_) (_)    |  Documentation: https://docs.julialang.org
   _ _   _| |_  __ _   |  Type "?help" for help.
  | | | | | | |/ _` |  |
  | | |_| | | | (_| |  |  Version 0.7.0-DEV.3404 (2018-01-14 21:52 UTC)
 _/ |\__'_|_|_|\__'_|  |  Commit d569a2923c* (30 days old master)
|__/                   |  x86_64-w64-mingw32

julia> f() = (const global x = 1)
f (generic function with 1 method)

julia> f()
1

julia> x = "a"
ERROR: invalid redefinition of constant x

julia> g() = (const global y = 1)
g (generic function with 1 method)

julia> y = 1
1

julia> g()
ERROR: cannot declare y constant; it already has a value
Stacktrace:
 [1] g() at .\REPL[4]:1
 [2] top-level scope
Knotted answered 14/2, 2018 at 8:15 Comment(0)
L
0

It looks like the behavior has changed since early 2018. On Julia 1.10.5 an error is reported.

julia> g() = (const global y = 1)
ERROR: syntax: `global const` declaration not allowed inside function around REPL[1]:1
Stacktrace:
 [1] top-level scope
   @ REPL[1]:1

julia> 
Lindgren answered 31/10 at 10:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.