Constants in Chapel

Constants in Chapel

Chapel supports constant values of character, string, boolean, and numeric types.

// Declare a constant value
const s: string = "constant";

proc main() {
  writeln(s);
  
  // A const statement can appear anywhere a var statement can
  const n = 500000000;
  
  // Constant expressions perform arithmetic with arbitrary precision
  const d = 3.0e20 / n;
  writeln(d);
  
  // Numeric constant has no type until given one, such as by an explicit conversion
  writeln(d: int);
  
  // A number can be given a type by using it in a context that requires one, 
  // such as a variable assignment or function call.
  // For example, here trig functions in Math module expect real(64) type.
  writeln(sin(n: real));
}

To run the program, save the code in a file named constants.chpl and use the chpl compiler to compile and then execute it.

$ chpl constants.chpl -o constants
$ ./constants
constant
6.0e+11
600000000000
-0.28470407323754404

This example shows how to declare and use constants in Chapel, demonstrating constant expressions, type conversion, and context-specific typing. Let’s dive deeper into Chapel’s features in the next examples.