Constants
C
C++
C#
Common Lisp
Dart
F#
Go
Java
JavaScript
Kotlin
Rust
You can define constants inside and outside a function.
Constants Across Different Languages
C
const int number1 = 1; // constant outside the function
int main(void)
{
const int number2 = 2; // constant inside the function
}
C++
You can define constants inside and outside a function using brace initialization or assignment.
const int number1 {1}; // constant outside the function
int main()
{
const int number2 {2}; // constant inside the function
}
C#
Constants can be defined at the class and method level.
class program
{
const int number1 = 1; // class-level constant
static void Main(string[] args)
{
const int number2 = 2; // method-level constant
Console.WriteLine(number2);
}
}
Common Lisp
(defconstant +number1+ 1)
Dart
You can define constants inside and outside a function.
const int number1 = 1; // constant calculated at compile time
final int number2 = 2; // constant calculated at runtime
F#
In F#, values are immutable by default:
let number = 123
Go
Go offers flexible ways to declare constants, including multiple declarations and the iota identifier.
const pi float64 = 3.1415
// Multiple declaration of constants
const (
pi float64 = 3.1415
e float64 = 2.7182
)
// Alternative option
const pi, e = 3.1415, 2.7182
// Declaration of constants with automatic initialization
const (
a = 1
b // b = 1
c // c = 1
d = 3
f // f = 3
)
// Using iota identifier to initialize constants
const (
C0 = iota // iota is 0, increases with each row
C1 // increase by 1, iota is 1
C2 = iota // iota is 2
)
Java
Constants can be defined at the class and method level using the final keyword.
class Program {
final int number0 = 0; // non-static class-level constant
final static int number1 = 1; // class-level static constant
public static void main(String[] args) {
final int number2 = 2; // method-level constant
System.out.println(number1);
System.out.println(number2);
}
}
JavaScript
You can define constants inside and outside a code block (function).
const number = 123;
To create completely constant objects (whose properties cannot be changed), use the Object.freeze() function:
const person = {name: "Tom", age: 37};
Object.freeze(person);
person.name = "Bob";
console.log(person.name); // Tom - the property value has not changed
Kotlin
Constants can only be defined outside of a function using the const keyword.
const val number = 1
fun main() {
println(number)
}
Rust
You can define constants at the code block level (for example, a function) and in the global scope:
const NUMBER1: i32 = 1; // global constant
fn main() {
const NUMBER2: i32 = 2; // function-level constant
println!("NUMBER1 = {}", NUMBER1);
println!("NUMBER2 = {}", NUMBER2);
}