Constants
Constants are values that cannot be changed after they’re defined. They’re useful for values that should remain fixed throughout your program.
Defining Constants
Section titled “Defining Constants”Use the constant keyword to define a constant:
constant PI = 3.14159constant MAX_USERS = 100constant COMPANY_NAME = "Acme Corp"constant TAX_RATE = 0.08Naming Conventions
Section titled “Naming Conventions”Constants are typically written in UPPERCASE with underscores:
constant MAX_LENGTH = 50constant DEFAULT_TIMEOUT = 30constant ERROR_MESSAGE = "An error occurred"constant DAYS_IN_WEEK = 7This makes it easy to distinguish constants from regular variables.
Using Constants
Section titled “Using Constants”Once defined, use constants like regular variables:
constant PI = 3.14159
radius = 5circumference = 2 * PI * radiusarea = PI * radius ^ 2
output "Circumference: {circumference}"output "Area: {area}"Constants Cannot Be Changed
Section titled “Constants Cannot Be Changed”Attempting to modify a constant will result in an error:
constant MAX_SCORE = 100
MAX_SCORE = 150 // Error: cannot reassign constantWhy Use Constants?
Section titled “Why Use Constants?”1. Prevent Accidental Changes
Section titled “1. Prevent Accidental Changes”constant SPEED_OF_LIGHT = 299792458 // meters per second
/* Later in code... SPEED_OF_LIGHT = 300000000 // Error - prevents mistakes */2. Improve Readability
Section titled “2. Improve Readability”// Without constants - unclear what 0.08 meanstotal = price + (price * 0.08)
// With constants - much clearerconstant TAX_RATE = 0.08total = price + (price * TAX_RATE)3. Easy Maintenance
Section titled “3. Easy Maintenance”// Define once, use everywhereconstant MAX_LOGIN_ATTEMPTS = 3
// Used in multiple placesattempts = 0while attempts < MAX_LOGIN_ATTEMPTS // login logic attempts++
if attempts >= MAX_LOGIN_ATTEMPTS output "Account locked"If you need to change the value, you only update it in one place!
Common Use Cases
Section titled “Common Use Cases”Mathematical Constants
Section titled “Mathematical Constants”constant PI = 3.14159265359constant E = 2.71828182846constant GOLDEN_RATIO = 1.61803398875
// Circle calculationsradius = 10circumference = 2 * PI * radiusarea = PI * radius ^ 2Configuration Values
Section titled “Configuration Values”constant MAX_FILE_SIZE = 1048576 // 1 MB in bytesconstant SESSION_TIMEOUT = 1800 // 30 minutes in secondsconstant MAX_RETRIES = 3constant DEFAULT_PORT = 8080Business Rules
Section titled “Business Rules”constant TAX_RATE = 0.08constant SHIPPING_COST = 5.99constant FREE_SHIPPING_THRESHOLD = 50.00constant DISCOUNT_RATE = 0.15
subtotal = 100tax = subtotal * TAX_RATE
if subtotal >= FREE_SHIPPING_THRESHOLD { shipping = 0} else { shipping = SHIPPING_COST}
total = subtotal + tax + shippingGame Development
Section titled “Game Development”constant SCREEN_WIDTH = 800constant SCREEN_HEIGHT = 600constant GRAVITY = 9.8constant PLAYER_SPEED = 5constant MAX_HEALTH = 100constant LEVEL_COUNT = 10
playerHealth = MAX_HEALTHcurrentLevel = 1
while currentLevel <= LEVEL_COUNT { // game logic currentLevel++}Validation Rules
Section titled “Validation Rules”constant MIN_PASSWORD_LENGTH = 8constant MAX_PASSWORD_LENGTH = 128constant MIN_AGE = 13constant MAX_AGE = 120constant MIN_USERNAME_LENGTH = 3constant MAX_USERNAME_LENGTH = 20
output "Enter password: "input password
if length of password < MIN_PASSWORD_LENGTH { output "Password must be at least {MIN_PASSWORD_LENGTH} characters"} else if length of password > MAX_PASSWORD_LENGTH { output "Password too long (max {MAX_PASSWORD_LENGTH} characters)"} else { output "Password accepted"}Examples
Section titled “Examples”Circle Calculator
Section titled “Circle Calculator”constant PI = 3.14159
output "Circle Calculator"output ""output "Enter radius: "input radiusInputradius = convert radiusInput to number
diameter = 2 * radiuscircumference = 2 * PI * radiusarea = PI * radius ^ 2
output ""output "Results:"output "Diameter: {diameter}"output "Circumference: {circumference}"output "Area: {area}"Shopping Cart
Section titled “Shopping Cart”constant TAX_RATE = 0.08constant SHIPPING_COST = 5.99constant FREE_SHIPPING_MINIMUM = 50.00constant MEMBER_DISCOUNT = 0.10
// Get cart totaloutput "Enter cart total: "input cartInputcartTotal = convert cartInput to number
// Check membershipoutput "Are you a member? (yes/no): "input memberInputisMember = memberInput equals "yes"
// Calculate subtotalsubtotal = cartTotal
// Apply member discountif isMember { discount = subtotal * MEMBER_DISCOUNT subtotal = subtotal - discount output "Member discount applied: ${discount}"}
// Calculate taxtax = subtotal * TAX_RATE
// Determine shippingif cartTotal >= FREE_SHIPPING_MINIMUM { shipping = 0 output "Free shipping!"} else { shipping = SHIPPING_COST}
// Calculate totaltotal = subtotal + tax + shipping
output ""output "Order Summary:"output "Subtotal: ${subtotal}"output "Tax: ${tax}"output "Shipping: ${shipping}"output "Total: ${total}"Temperature Converter
Section titled “Temperature Converter”constant FAHRENHEIT_OFFSET = 32constant FAHRENHEIT_SCALE = 5 / 9
output "Temperature Converter"output ""output "1. Fahrenheit to Celsius"output "2. Celsius to Fahrenheit"output "Enter choice: "input choicechoice = convert choice to number
output "Enter temperature: "input tempInputtemp = convert tempInput to number
if choice equals 1 { celsius = (temp - FAHRENHEIT_OFFSET) * FAHRENHEIT_SCALE output "{temp}°F = {celsius}°C"} else if choice equals 2 { fahrenheit = (temp / FAHRENHEIT_SCALE) + FAHRENHEIT_OFFSET output "{temp}°C = {fahrenheit}°F"} else { output "Invalid choice"}Grade Boundaries
Section titled “Grade Boundaries”constant GRADE_A_MIN = 90constant GRADE_B_MIN = 80constant GRADE_C_MIN = 70constant GRADE_D_MIN = 60constant MAX_SCORE = 100
output "Enter score (0-100): "input scoreInputscore = convert scoreInput to number
if score < 0 OR score > MAX_SCORE { output "Invalid score"} else if score >= GRADE_A_MIN { output "Grade: A"} else if score >= GRADE_B_MIN { output "Grade: B"} else if score >= GRADE_C_MIN { output "Grade: C"} else if score >= GRADE_D_MIN { output "Grade: D"} else { output "Grade: F"}Retry Logic
Section titled “Retry Logic”constant MAX_ATTEMPTS = 3constant CORRECT_PASSWORD = "secret123"
attempts = 0authenticated = false
while attempts < MAX_ATTEMPTS AND NOT authenticated { output "Enter password (Attempt {attempts + 1} of {MAX_ATTEMPTS}): " input password
if password equals CORRECT_PASSWORD { authenticated = true output "Access granted!" } else { attempts++ remaining = MAX_ATTEMPTS - attempts if remaining > 0 output "Incorrect. {remaining} attempts remaining." }}
if NOT authenticated output "Access denied. Account locked."Constants vs Variables
Section titled “Constants vs Variables”Use Constants When:
Section titled “Use Constants When:”- Value should never change
- Value represents a fundamental constant (like π)
- Value is a configuration setting
- Value defines business rules or limits
constant MAX_INVENTORY = 1000constant DEFAULT_CURRENCY = "USD"Use Variables When:
Section titled “Use Variables When:”- Value will change during program execution
- Value depends on user input or calculations
- Value represents program state
currentInventory = 500 // Will change as items are solduserCurrency = "EUR" // User can select different currencyBest Practices
Section titled “Best Practices”-
Use UPPERCASE names
constant MAX_SIZE = 100 // Goodconstant maxSize = 100 // Less clear -
Group related constants
// Database configurationconstant DB_HOST = "localhost"constant DB_PORT = 5432constant DB_NAME = "myapp"// UI configurationconstant SCREEN_WIDTH = 1920constant SCREEN_HEIGHT = 1080constant THEME_COLOR = "blue" -
Define constants at the top
// All constants defined firstconstant TAX_RATE = 0.08constant SHIPPING_COST = 5.99constant MAX_ITEMS = 100// Then your program logiccartTotal = 0itemCount = 0 -
Use descriptive names
constant TIMEOUT_SECONDS = 30 // Goodconstant T = 30 // Badconstant MAX_LOGIN_ATTEMPTS = 3 // Goodconstant MLA = 3 // Bad -
Document magic numbers
// Instead of:if temperature > 100 {output "Water is boiling"}// Use:constant WATER_BOILING_POINT = 100if temperature > WATER_BOILING_POINT {output "Water is boiling"}