ProtoLang.net

Reference: If

☰ Hide Sidebar
TOKEN IF
ALIAS None

The If token is used to execute code blocks based on Boolean conditions. When the condition evaluates to True, the code inside the If block runs. When the condition evaluates to False, the code is skipped. If statements can be extended with Elif (else if) and Else clauses to handle multiple conditions and default cases.

Syntax

The short syntax structure uses the words IF, ELIF, ELSE, and END IF:

IF CONDITION
    STATEMENTS
END IF

The long syntax structure uses the same words:

IF CONDITION
    STATEMENTS
END IF

Basic If Statement

The simplest form of an If statement checks a single condition and executes code only when that condition is True.

Example: Simple If Statement

NEW INT age = 20
IF age >= 18
    PRINTLN "You are an adult"
END IF
// Displays "You are an adult"

Example: If with Boolean Variable

NEW BOOL isLoggedIn = TRUE
IF isLoggedIn == TRUE
    PRINTLN "Welcome back!"
END IF
// Displays "Welcome back!"

Example: If with Comparison

NEW INT score = 85
IF score > 80
    PRINTLN "Excellent score!"
END IF
// Displays "Excellent score!"

Example: If that Doesn't Execute

NEW FLOAT temperature = 65.0
IF temperature > 100.0
    PRINTLN "It's very hot!"
END IF
// Nothing is displayed because condition is False

If-Else Statement

The Else clause provides an alternative code block that executes when the If condition is False.

Example: Basic If-Else

NEW INT age = 16
IF age >= 18
    PRINTLN "You can vote"
ELSE
    PRINTLN "You cannot vote yet"
END IF
// Displays "You cannot vote yet"

Example: If-Else with Boolean

NEW BOOL hasAccess = FALSE
IF hasAccess == TRUE
    PRINTLN "Access granted"
ELSE
    PRINTLN "Access denied"
END IF
// Displays "Access denied"

Example: If-Else with String Comparison

NEW STR password = "secret123"
IF password == "admin123"
    PRINTLN "Admin login successful"
ELSE
    PRINTLN "Invalid password"
END IF
// Displays "Invalid password"

Example: If-Else with Float Comparison

NEW FLOAT price = 19.99
IF price <= 20.00
    PRINTLN "Affordable"
ELSE
    PRINTLN "Too expensive"
END IF
// Displays "Affordable"

If-Elif-Else Statement

The Elif (else if) clause allows you to check multiple conditions in sequence. The first condition that evaluates to True will have its code block executed, and all subsequent conditions will be skipped.

Example: Multiple Conditions with Elif

NEW INT score = 85
IF score >= 90
    PRINTLN "Grade: A"
ELIF score >= 80
    PRINTLN "Grade: B"
ELIF score >= 70
    PRINTLN "Grade: C"
ELIF score >= 60
    PRINTLN "Grade: D"
ELSE
    PRINTLN "Grade: F"
END IF
// Displays "Grade: B"

Example: Temperature Classification

NEW FLOAT temp = 75.0
IF temp >= 90.0
    PRINTLN "Very hot"
ELIF temp >= 75.0
    PRINTLN "Warm"
ELIF temp >= 60.0
    PRINTLN "Mild"
ELIF temp >= 40.0
    PRINTLN "Cool"
ELSE
    PRINTLN "Cold"
END IF
// Displays "Warm"

Example: Multiple Elif Clauses

NEW INT day = 3
IF day == 1
    PRINTLN "Monday"
ELIF day == 2
    PRINTLN "Tuesday"
ELIF day == 3
    PRINTLN "Wednesday"
ELIF day == 4
    PRINTLN "Thursday"
ELIF day == 5
    PRINTLN "Friday"
ELIF day == 6
    PRINTLN "Saturday"
ELIF day == 7
    PRINTLN "Sunday"
ELSE
    PRINTLN "Invalid day"
END IF
// Displays "Wednesday"

Example: Elif with String Comparison

NEW STR status = "pending"
IF status == "complete"
    PRINTLN "Task finished"
ELIF status == "pending"
    PRINTLN "Task in progress"
ELIF status == "cancelled"
    PRINTLN "Task cancelled"
ELSE
    PRINTLN "Unknown status"
END IF
// Displays "Task in progress"

Using Logical Operators in Conditions

If conditions can use And and Or operators to create complex conditions.

Example: If with And Operator

NEW INT age = 25
NEW BOOL hasLicense = TRUE
IF ( age >= 18 ) && hasLicense
    PRINTLN "You can drive"
ELSE
    PRINTLN "You cannot drive"
END IF
// Displays "You can drive"

Example: If with Or Operator

NEW BOOL isWeekend = FALSE
NEW BOOL isHoliday = TRUE
IF isWeekend || isHoliday
    PRINTLN "Day off!"
ELSE
    PRINTLN "Work day"
END IF
// Displays "Day off!"

Example: Complex Condition with And and Or

NEW INT age = 16
NEW BOOL hasPermit = TRUE
NEW BOOL withAdult = TRUE
IF ( age >= 18 ) || ( ( age >= 16 ) && hasPermit && withAdult )
    PRINTLN "Can drive"
ELSE
    PRINTLN "Cannot drive"
END IF
// Displays "Can drive"

Example: Multiple And Conditions

NEW STR username = "admin"
NEW STR password = "pass123"
NEW INT twoFactorCode = 5678
IF ( username == "admin" ) && ( password == "pass123" ) && ( twoFactorCode == 5678 )
    PRINTLN "Login successful"
ELSE
    PRINTLN "Login failed"
END IF
// Displays "Login successful"

Nested If Statements

If statements can be placed inside other If statements to create nested conditions.

Example: Basic Nested If

NEW INT age = 25
NEW BOOL hasTicket = TRUE
IF age >= 18
    IF hasTicket == TRUE
        PRINTLN "You can enter"
    ELSE
        PRINTLN "You need a ticket"
    END IF
ELSE
    PRINTLN "You must be 18 or older"
END IF
// Displays "You can enter"

Example: Nested If-Else

NEW INT score = 85
NEW INT attendance = 95
IF score >= 60
    IF attendance >= 80
        PRINTLN "Pass with good attendance"
    ELSE
        PRINTLN "Pass but poor attendance"
    END IF
ELSE
    PRINTLN "Fail"
END IF
// Displays "Pass with good attendance"

Example: Multiple Levels of Nesting

NEW STR userType = "admin"
NEW BOOL isActive = TRUE
NEW BOOL hasPermission = TRUE
IF userType == "admin"
    IF isActive == TRUE
        IF hasPermission == TRUE
            PRINTLN "Full access granted"
        ELSE
            PRINTLN "Access limited - no permission"
        END IF
    ELSE
        PRINTLN "Account inactive"
    END IF
ELSE
    PRINTLN "Not an admin"
END IF
// Displays "Full access granted"

Example: Nested If with Elif

NEW STR category = "premium"
NEW INT points = 150
IF category == "premium"
    IF points >= 100
        PRINTLN "Premium member with bonus"
    ELIF points >= 50
        PRINTLN "Premium member"
    ELSE
        PRINTLN "New premium member"
    END IF
ELSE
    PRINTLN "Standard member"
END IF
// Displays "Premium member with bonus"

Modifying Variables in If Blocks

Variables can be created or modified inside If blocks using New and Set commands.

Example: Setting Variable in If

NEW INT score = 85
NEW STR grade = ""
IF score >= 90
    SET grade = "A"
ELIF score >= 80
    SET grade = "B"
ELIF score >= 70
    SET grade = "C"
ELSE
    SET grade = "F"
END IF
PRINTLN "Your grade is: " .. grade
// Displays "Your grade is: B"

Example: Incrementing in If

NEW INT points = 100
NEW INT bonus = 0
IF points >= 100
    SET bonus = 50
    SET points = points + bonus
END IF
PRINTLN "Total points: " .. points
// Displays "Total points: 150"

Example: Multiple Variable Updates

NEW FLOAT balance = 1000.0
NEW FLOAT fee = 0.0
NEW STR status = "pending"
IF balance >= 500.0
    SET fee = 0.0
    SET status = "approved"
ELSE
    SET fee = 25.0
    SET status = "rejected"
END IF
PRINTLN "Status: " .. status
PRINTLN "Fee: " .. fee
// Displays "Status: approved" and "Fee: 0.0"

Example: Conditional Accumulation

NEW INT total = 0
NEW INT value = 15
IF value > 10
    SET total = total + value
END IF
PRINTLN "Total: " .. total
// Displays "Total: 15"

Using If with Expressions

If conditions can evaluate complex Expressions that use arithmetic, comparison, and logical operators.

Example: Arithmetic in Condition

NEW INT x = 10
NEW INT y = 5
IF ( x + y ) > 10
    PRINTLN "Sum is greater than 10"
END IF
// Displays "Sum is greater than 10"

Example: Modulo in Condition

NEW INT number = 8
IF ( number % 2 ) == 0
    PRINTLN "Even number"
ELSE
    PRINTLN "Odd number"
END IF
// Displays "Even number"

Example: Multiple Expressions

NEW INT a = 5
NEW INT b = 3
NEW INT c = 8
IF ( a + b ) == c
    PRINTLN "Equation is correct"
ELSE
    PRINTLN "Equation is incorrect"
END IF
// Displays "Equation is correct"

Example: Complex Expression with Comparison

NEW FLOAT price = 100.0
NEW FLOAT discount = 0.20
NEW FLOAT finalPrice = price - ( price * discount )
IF finalPrice < 100.0
    PRINTLN "Discounted price: " .. finalPrice
END IF
// Displays "Discounted price: 80.0"

Practical Applications

Example: User Authentication

NEW STR username = "alice"
NEW STR password = "secret123"
NEW INT attempts = 3
IF ( username == "alice" ) && ( password == "secret123" )
    PRINTLN "Login successful"
    SET attempts = 0
ELSE
    SET attempts = attempts - 1
    PRINTLN "Login failed. Attempts remaining: " .. attempts
END IF

Example: Age Group Classification

NEW INT age = 35
NEW STR category = ""
IF age < 13
    SET category = "Child"
ELIF age < 20
    SET category = "Teenager"
ELIF age < 60
    SET category = "Adult"
ELSE
    SET category = "Senior"
END IF
PRINTLN "Age category: " .. category
// Displays "Age category: Adult"

Example: Temperature Alert System

NEW FLOAT temp = 105.0
NEW STR alert = "Normal"
IF temp > 100.0
    SET alert = "Critical - High Temperature"
ELIF temp > 90.0
    SET alert = "Warning - Elevated Temperature"
ELIF temp < 32.0
    SET alert = "Warning - Freezing Temperature"
END IF
PRINTLN "Status: " .. alert
// Displays "Status: Critical - High Temperature"

Example: Discount Calculator

NEW FLOAT purchaseAmount = 150.0
NEW FLOAT discountRate = 0.0
NEW BOOL isMember = TRUE
IF isMember == TRUE
    IF purchaseAmount >= 200.0
        SET discountRate = 0.20
    ELIF purchaseAmount >= 100.0
        SET discountRate = 0.15
    ELIF purchaseAmount >= 50.0
        SET discountRate = 0.10
    END IF
ELSE
    IF purchaseAmount >= 200.0
        SET discountRate = 0.10
    END IF
END IF
NEW FLOAT finalAmount = purchaseAmount - ( purchaseAmount * discountRate )
PRINTLN "Discount: " .. ( discountRate * 100.0 ) .. "%"
PRINTLN "Final amount: " .. finalAmount
// Displays "Discount: 15.0%" and "Final amount: 127.5"

Example: Grade Calculator with Multiple Criteria

NEW INT examScore = 75
NEW INT homeworkScore = 85
NEW INT attendance = 90
NEW STR finalGrade = ""
NEW INT averageScore = ( examScore + homeworkScore ) / 2
IF ( averageScore >= 90 ) && ( attendance >= 80 )
    SET finalGrade = "A"
ELIF ( averageScore >= 80 ) && ( attendance >= 75 )
    SET finalGrade = "B"
ELIF ( averageScore >= 70 ) && ( attendance >= 70 )
    SET finalGrade = "C"
ELIF averageScore >= 60
    SET finalGrade = "D"
ELSE
    SET finalGrade = "F"
END IF
PRINTLN "Final Grade: " .. finalGrade
// Displays "Final Grade: C"

Example: Shipping Cost Calculator

NEW FLOAT weight = 5.5
NEW INT distance = 250
NEW FLOAT shippingCost = 0.0
IF weight <= 1.0
    IF distance <= 100
        SET shippingCost = 5.0
    ELSE
        SET shippingCost = 10.0
    END IF
ELIF weight <= 5.0
    IF distance <= 100
        SET shippingCost = 10.0
    ELSE
        SET shippingCost = 20.0
    END IF
ELSE
    IF distance <= 100
        SET shippingCost = 20.0
    ELSE
        SET shippingCost = 35.0
    END IF
END IF
PRINTLN "Shipping cost: $" .. shippingCost
// Displays "Shipping cost: $35.0"

Example: Game Score Evaluation

NEW INT playerScore = 2500
NEW INT playerLevel = 5
NEW STR achievement = "None"
IF playerScore >= 5000
    SET achievement = "Master"
ELIF playerScore >= 3000
    SET achievement = "Expert"
ELIF playerScore >= 1000
    IF playerLevel >= 5
        SET achievement = "Advanced"
    ELSE
        SET achievement = "Intermediate"
    END IF
ELSE
    SET achievement = "Beginner"
END IF
PRINTLN "Achievement level: " .. achievement
// Displays "Achievement level: Advanced"

Example: Loan Approval System

NEW INT creditScore = 720
NEW FLOAT income = 50000.0
NEW FLOAT debtRatio = 0.30
NEW BOOL approved = FALSE
NEW FLOAT loanAmount = 0.0
IF ( creditScore >= 700 ) && ( income >= 40000.0 ) && ( debtRatio <= 0.40 )
    SET approved = TRUE
    IF creditScore >= 750
        SET loanAmount = 100000.0
    ELIF creditScore >= 700
        SET loanAmount = 75000.0
    END IF
ELIF ( creditScore >= 650 ) && ( income >= 50000.0 ) && ( debtRatio <= 0.30 )
    SET approved = TRUE
    SET loanAmount = 50000.0
END IF
IF approved == TRUE
    PRINTLN "Loan approved for: $" .. loanAmount
ELSE
    PRINTLN "Loan denied"
END IF
// Displays "Loan approved for: $75000.0"

If Statements with Print Commands

Example: Conditional Output

NEW INT count = 5
IF count > 0
    PRINTLN "Count is positive: " .. count
END IF
// Displays "Count is positive: 5"

Example: Multiple Print Statements

NEW STR status = "active"
IF status == "active"
    PRINTLN "System Status: ACTIVE"
    PRINTLN "All systems operational"
    PRINTLN "Ready for use"
END IF
// Displays three lines of output

Example: Print in Each Branch

NEW INT level = 2
IF level == 1
    PRINTLN "Beginner level"
ELIF level == 2
    PRINTLN "Intermediate level"
ELIF level == 3
    PRINTLN "Advanced level"
ELSE
    PRINTLN "Unknown level"
END IF
// Displays "Intermediate level"

Using If with All Data Types

Example: Boolean Conditions

NEW BOOL isEnabled = TRUE
NEW BOOL isReady = FALSE
IF isEnabled == TRUE
    PRINTLN "Feature is enabled"
END IF
IF isReady == FALSE
    PRINTLN "System not ready"
END IF
// Displays "Feature is enabled" and "System not ready"

Example: Integer Conditions

NEW INT quantity = 10
NEW INT minQuantity = 5
NEW INT maxQuantity = 20
IF quantity >= minQuantity
    IF quantity <= maxQuantity
        PRINTLN "Quantity is within range"
    ELSE
        PRINTLN "Quantity exceeds maximum"
    END IF
ELSE
    PRINTLN "Quantity below minimum"
END IF
// Displays "Quantity is within range"

Example: Float Conditions

NEW FLOAT temperature = 98.6
NEW FLOAT normalTemp = 98.6
IF temperature == normalTemp
    PRINTLN "Temperature is normal"
ELIF temperature > normalTemp
    PRINTLN "Temperature is high"
ELSE
    PRINTLN "Temperature is low"
END IF
// Displays "Temperature is normal"

Example: String Conditions

NEW STR command = "start"
IF command == "start"
    PRINTLN "Starting system..."
ELIF command == "stop"
    PRINTLN "Stopping system..."
ELIF command == "restart"
    PRINTLN "Restarting system..."
ELSE
    PRINTLN "Unknown command"
END IF
// Displays "Starting system..."

If Statements in Loops

Example: If Inside While Loop

NEW INT i = 1
WHILE i <= 5
    IF ( i % 2 ) == 0
        PRINTLN i .. " is even"
    ELSE
        PRINTLN i .. " is odd"
    END IF
    SET i = i + 1
END WHILE
// Displays: 1 is odd, 2 is even, 3 is odd, 4 is even, 5 is odd

Example: Conditional Loop Break

NEW INT counter = 1
NEW INT target = 7
WHILE counter <= 10
    IF counter == target
        PRINTLN "Target found: " .. target
        BREAK
    END IF
    SET counter = counter + 1
END WHILE
// Displays "Target found: 7"

Example: Filtering in Loop

NEW INT i = 1
NEW INT sum = 0
WHILE i <= 10
    IF i > 5
        SET sum = sum + i
    END IF
    SET i = i + 1
END WHILE
PRINTLN "Sum of numbers greater than 5: " .. sum
// Displays "Sum of numbers greater than 5: 40"

Example: Multiple Conditions in Loop

NEW INT n = 1
WHILE n <= 20
    IF ( n % 3 ) == 0
        IF ( n % 5 ) == 0
            PRINTLN n .. " is divisible by both 3 and 5"
        ELSE
            PRINTLN n .. " is divisible by 3"
        END IF
    ELIF ( n % 5 ) == 0
        PRINTLN n .. " is divisible by 5"
    END IF
    SET n = n + 1
END WHILE

Comparison Operators in If Statements

Example: All Comparison Operators

NEW INT value = 50
IF value == 50
    PRINTLN "Equal to 50"
END IF
IF value != 40
    PRINTLN "Not equal to 40"
END IF
IF value > 30
    PRINTLN "Greater than 30"
END IF
IF value >= 50
    PRINTLN "Greater than or equal to 50"
END IF
IF value < 100
    PRINTLN "Less than 100"
END IF
IF value <= 50
    PRINTLN "Less than or equal to 50"
END IF
// Displays all six messages

Example: Chaining Comparisons with Elif

NEW INT x = 75
IF x < 50
    PRINTLN "Low"
ELIF x < 75
    PRINTLN "Medium"
ELIF x < 100
    PRINTLN "High"
ELSE
    PRINTLN "Very High"
END IF
// Displays "High"

Edge Cases and Special Scenarios

Example: Empty If Block ( Valid but Does Nothing )

NEW INT x = 5
IF x > 10
    // Condition is false, this block doesn't execute
END IF
PRINTLN "Program continues"
// Displays "Program continues"

Example: Checking for Zero

NEW INT divisor = 0
IF divisor == 0
    PRINTLN "Cannot divide by zero"
ELSE
    NEW INT result = 10 / divisor
    PRINTLN "Result: " .. result
END IF
// Displays "Cannot divide by zero"

Example: Negative Number Handling

NEW INT balance = -50
IF balance < 0
    PRINTLN "Negative balance: " .. balance
    PRINTLN "Account overdrawn"
ELIF balance == 0
    PRINTLN "Zero balance"
ELSE
    PRINTLN "Positive balance: " .. balance
END IF
// Displays "Negative balance: -50" and "Account overdrawn"

Example: Case-Sensitive String Comparison

NEW STR input = "Yes"
IF input == "yes"
    PRINTLN "Lowercase match"
ELIF input == "Yes"
    PRINTLN "Capitalized match"
ELIF input == "YES"
    PRINTLN "Uppercase match"
ELSE
    PRINTLN "No match"
END IF
// Displays "Capitalized match"

Structure and Indentation

ProtoLang If statements should be properly indented for readability, though whitespace before and after statements is flexible.

Example: Proper Indentation

NEW INT age = 20
IF age >= 18
    PRINTLN "Adult"
    IF age >= 21
        PRINTLN "Can drink alcohol"
    ELSE
        PRINTLN "Cannot drink alcohol yet"
    END IF
ELSE
    PRINTLN "Minor"
END IF

Important Notes

  • Every If statement must end with END IF.
  • Conditions must evaluate to a Boolean value ( True or False ).
  • Elif clauses are optional and can appear multiple times.
  • Else clause is optional and can appear only once at the end.
  • Only the first True condition's code block executes; subsequent conditions are skipped.
  • If statements can be nested to any depth.
  • Variables modified inside If blocks affect the global scope ( unless inside a function ).
  • Use parentheses in complex conditions to make logic clear.
  • String comparisons are case-sensitive.
  • All Comparison Operators can be used in If conditions.

Common Errors

Error: Missing END IF

NEW INT x = 5
IF x > 3
    PRINTLN "Greater than 3"
// Syntax error! Missing END IF
// Correct:
NEW INT y = 5
IF y > 3
    PRINTLN "Greater than 3"
END IF

Error: Using Non-Boolean Condition

NEW INT x = 5
IF x // Runtime error! Condition must be Boolean
    PRINTLN "This won't work"
END IF
// Correct:
IF x > 0
    PRINTLN "x is positive"
END IF

Error: Else Before Elif

NEW INT score = 75
IF score >= 90
    PRINTLN "A"
ELSE
    PRINTLN "Not an A"
ELIF score >= 80 // Syntax error! ELIF cannot come after ELSE
    PRINTLN "B"
END IF
// Correct:
IF score >= 90
    PRINTLN "A"
ELIF score >= 80
    PRINTLN "B"
ELSE
    PRINTLN "Not A or B"
END IF

Error: Using Assignment Instead of Comparison

NEW INT x = 5
IF x = 5 // Syntax error! Use == for comparison, not =
    PRINTLN "x is 5"
END IF
// Correct:
IF x == 5
    PRINTLN "x is 5"
END IF

Error: Comparing Different Data Types

NEW INT x = 5
NEW STR y = "5"
IF x == y // Type error! Cannot compare Integer and String
    PRINTLN "Equal"
END IF
// Correct: Compare same types
NEW INT a = 5
NEW INT b = 5
IF a == b
    PRINTLN "Equal"
END IF

Error: Mixing Integer and Float in Comparison

NEW INT x = 5
NEW FLOAT y = 5.0
IF x == y // Type error! Cannot compare Integer and Float
    PRINTLN "Equal"
END IF
// Correct: Use same type
NEW INT a = 5
NEW INT b = 5
IF a == b
    PRINTLN "Equal"
END IF

Error: Forgetting Parentheses in Complex Conditions

NEW INT age = 25
NEW BOOL hasLicense = TRUE
// Ambiguous without parentheses
IF age >= 18 && hasLicense // May cause confusion
    PRINTLN "Can drive"
END IF
// Correct: Use parentheses for clarity
IF ( age >= 18 ) && hasLicense
    PRINTLN "Can drive"
END IF

Error: Case Sensitivity in String Comparison

NEW STR answer = "YES"
IF answer == "yes" // Will be False due to case difference
    PRINTLN "Confirmed"
ELSE
    PRINTLN "Not confirmed"
END IF
// Displays "Not confirmed"
// Correct: Match the case
IF answer == "YES"
    PRINTLN "Confirmed"
END IF

Error: Multiple Else Clauses

NEW INT x = 5
IF x > 10
    PRINTLN "Greater than 10"
ELSE
    PRINTLN "Not greater than 10"
ELSE // Syntax error! Only one ELSE allowed
    PRINTLN "This is wrong"
END IF
// Correct: Use ELIF for additional conditions
IF x > 10
    PRINTLN "Greater than 10"
ELIF x > 5
    PRINTLN "Greater than 5"
ELSE
    PRINTLN "5 or less"
END IF

Error: If Without Condition

IF // Syntax error! Missing condition
    PRINTLN "This won't work"
END IF
// Correct: Provide a Boolean condition
NEW BOOL ready = TRUE
IF ready == TRUE
    PRINTLN "Ready to proceed"
END IF