ProtoLang.net

Reference: Return

☰ Hide Sidebar
TOKEN RETURN
ALIAS None

The Return token is used inside Functions to send a value back to the caller and immediately exit the function. When a Return statement executes, the function stops running and control returns to the point where the function was called, along with the specified return value.

Syntax

The short syntax structure uses the word RETURN:

FUNCTION NAME ( PARAMETERS )
    STATEMENTS
    RETURN VALUE
END FUNCTION

The long syntax structure uses the word RETURN:

FUNCTION NAME GROUP PARAMETERS END GROUP
    STATEMENTS
    RETURN VALUE
END FUNCTION

How Return Works

The Return statement performs two actions:

  1. Specifies the value to send back to the function caller
  2. Immediately exits the function, skipping any remaining code in the function body

Example: Basic Return

FUNCTION getValue ( )
    NEW INT result = 42
    RETURN result
END FUNCTION

NEW INT x = getValue ( )
PRINTLN x // Displays: 42

Returning Different Data Types

Example: Returning Integer

FUNCTION add ( INT a , INT b )
    NEW INT sum = a + b
    RETURN sum
END FUNCTION

NEW INT result = add ( 5 , 3 )
PRINTLN result // Displays: 8

Example: Returning Float

FUNCTION calculateArea ( FLOAT width , FLOAT height )
    NEW FLOAT area = width * height
    RETURN area
END FUNCTION

NEW FLOAT roomArea = calculateArea ( 10.5 , 8.0 )
PRINTLN roomArea // Displays: 84.0

Example: Returning String

FUNCTION greet ( STR name )
    NEW STR message = "Hello, " .. name .. "!"
    RETURN message
END FUNCTION

NEW STR greeting = greet ( "Alice" )
PRINTLN greeting // Displays: Hello, Alice!

Example: Returning Boolean

FUNCTION isEven ( INT number )
    NEW BOOL result = ( number % 2 ) == 0
    RETURN result
END FUNCTION

NEW BOOL check = isEven ( 4 )
PRINTLN check // Displays: TRUE

Returning Literal Values

Return can send back literal values directly without storing them in a variable first.

Example: Returning Integer Literal

FUNCTION getMax ( )
    RETURN 100
END FUNCTION

NEW INT maximum = getMax ( )
PRINTLN maximum // Displays: 100

Example: Returning Float Literal

FUNCTION getPi ( )
    RETURN 3.14159
END FUNCTION

NEW FLOAT pi = getPi ( )
PRINTLN pi // Displays: 3.14159

Example: Returning String Literal

FUNCTION getStatus ( )
    RETURN "Active"
END FUNCTION

NEW STR status = getStatus ( )
PRINTLN status // Displays: Active

Example: Returning Boolean Literal

FUNCTION isReady ( )
    RETURN TRUE
END FUNCTION

NEW BOOL ready = isReady ( )
PRINTLN ready // Displays: TRUE

Returning Expression Results

Return can send back the result of an Expression directly.

Example: Returning Arithmetic Expression

FUNCTION multiply ( INT a , INT b )
    RETURN a * b
END FUNCTION

NEW INT product = multiply ( 6 , 7 )
PRINTLN product // Displays: 42

Example: Returning Comparison Expression

FUNCTION isGreater ( INT a , INT b )
    RETURN a > b
END FUNCTION

NEW BOOL result = isGreater ( 10 , 5 )
PRINTLN result // Displays: TRUE

Example: Returning String Concatenation

FUNCTION makeLabel ( STR key , INT value )
    RETURN key .. ": " .. value
END FUNCTION

NEW STR label = makeLabel ( "Score" , 95 )
PRINTLN label // Displays: Score: 95

Example: Returning Complex Expression

FUNCTION calculate ( INT x , INT y )
    RETURN ( x + y ) * 2
END FUNCTION

NEW INT result = calculate ( 5 , 3 )
PRINTLN result // Displays: 16

Return with Conditionals

Return statements can appear in different branches of If statements.

Example: Conditional Return

FUNCTION getSign ( INT n )
    IF n > 0
        RETURN "positive"
    ELIF n < 0
        RETURN "negative"
    ELSE
        RETURN "zero"
    END IF
END FUNCTION

PRINTLN getSign ( 10 ) // Displays: positive
PRINTLN getSign ( -5 ) // Displays: negative
PRINTLN getSign ( 0 ) // Displays: zero

Example: Early Return

FUNCTION checkValue ( INT n )
    IF n < 0
        RETURN "Invalid"
    END IF
    
    IF n == 0
        RETURN "Zero"
    END IF
    
    RETURN "Valid"
END FUNCTION

PRINTLN checkValue ( -5 ) // Displays: Invalid
PRINTLN checkValue ( 0 ) // Displays: Zero
PRINTLN checkValue ( 10 ) // Displays: Valid

Example: Return Different Types in Branches

FUNCTION getGrade ( INT score )
    IF score >= 90
        RETURN "A"
    ELIF score >= 80
        RETURN "B"
    ELIF score >= 70
        RETURN "C"
    ELIF score >= 60
        RETURN "D"
    ELSE
        RETURN "F"
    END IF
END FUNCTION

NEW STR grade = getGrade ( 85 )
PRINTLN grade // Displays: B

Example: Guard Clauses

FUNCTION divide ( INT a , INT b )
    IF b == 0
        RETURN 0 // Guard against division by zero
    END IF
    
    RETURN a / b
END FUNCTION

NEW INT result = divide ( 10 , 2 )
PRINTLN result // Displays: 5
NEW INT safe = divide ( 10 , 0 )
PRINTLN safe // Displays: 0

Return Exits Function Immediately

When Return executes, the function stops immediately and any code after the Return is not executed.

Example: Code After Return Not Executed

FUNCTION test ( )
    PRINTLN "Before return"
    RETURN 42
    PRINTLN "After return" // This never executes
END FUNCTION

NEW INT value = test ( )
// Only displays: Before return
PRINTLN value // Displays: 42

Example: Early Exit

FUNCTION process ( INT n )
    PRINTLN "Starting"
    
    IF n < 0
        PRINTLN "Negative detected"
        RETURN -1 // Exit early
    END IF
    
    PRINTLN "Processing positive number"
    RETURN n * 2
END FUNCTION

NEW INT result1 = process ( -5 )
// Displays: Starting, Negative detected

NEW INT result2 = process ( 5 )
// Displays: Starting, Processing positive number

Example: Loop with Early Return

FUNCTION findFirst ( INT target )
    NEW INT i = 1
    WHILE i <= 10
        IF i == target
            RETURN i // Exit function immediately
        END IF
        SET i = i + 1
    END WHILE
    RETURN -1 // Not found
END FUNCTION

NEW INT found = findFirst ( 5 )
PRINTLN found // Displays: 5

Return in Loops

Return can be used inside While loops to exit both the loop and the function.

Example: Search Function

FUNCTION search ( INT target , INT max )
    NEW INT i = 1
    WHILE i <= max
        IF i == target
            RETURN i
        END IF
        SET i = i + 1
    END WHILE
    RETURN -1
END FUNCTION

NEW INT found = search ( 7 , 10 )
PRINTLN found // Displays: 7
NEW INT notFound = search ( 15 , 10 )
PRINTLN notFound // Displays: -1

Example: Validation Loop

FUNCTION hasEven ( INT start , INT end )
    NEW INT i = start
    WHILE i <= end
        IF i % 2 == 0
            RETURN TRUE // Found even number
        END IF
        SET i = i + 1
    END WHILE
    RETURN FALSE // No even numbers found
END FUNCTION

NEW BOOL result = hasEven ( 1 , 5 )
PRINTLN result // Displays: TRUE

Example: Accumulator with Early Exit

FUNCTION sumUntilLimit ( INT limit )
    NEW INT sum = 0
    NEW INT i = 1
    WHILE i <= 100
        SET sum = sum + i
        IF sum >= limit
            RETURN sum // Exit when limit reached
        END IF
        SET i = i + 1
    END WHILE
    RETURN sum
END FUNCTION

NEW INT total = sumUntilLimit ( 50 )
PRINTLN total // Displays first sum >= 50

Multiple Return Statements

Functions can have multiple Return statements in different code paths.

Example: Multiple Returns

FUNCTION classify ( INT n )
    IF n < 0
        RETURN "negative"
    END IF
    
    IF n == 0
        RETURN "zero"
    END IF
    
    IF n < 10
        RETURN "small"
    END IF
    
    IF n < 100
        RETURN "medium"
    END IF
    
    RETURN "large"
END FUNCTION

PRINTLN classify ( -5 ) // Displays: negative
PRINTLN classify ( 0 ) // Displays: zero
PRINTLN classify ( 5 ) // Displays: small
PRINTLN classify ( 50 ) // Displays: medium
PRINTLN classify ( 150 ) // Displays: large

Example: Error Handling Pattern

FUNCTION safeDivide ( INT a , INT b )
    IF b == 0
        RETURN 0
    END IF
    
    IF a == 0
        RETURN 0
    END IF
    
    RETURN a / b
END FUNCTION

PRINTLN safeDivide ( 10 , 2 ) // Displays: 5
PRINTLN safeDivide ( 10 , 0 ) // Displays: 0
PRINTLN safeDivide ( 0 , 5 ) // Displays: 0

Return Value Usage

The value returned by a function can be used in various ways.

Example: Assign to Variable

FUNCTION double ( INT n )
    RETURN n * 2
END FUNCTION

NEW INT result = double ( 5 )
PRINTLN result // Displays: 10

Example: Use in Expression

FUNCTION square ( INT n )
    RETURN n * n
END FUNCTION

NEW INT x = 5
NEW INT result = square ( x ) + 10
PRINTLN result // Displays: 35

Example: Use in Print Statement

FUNCTION getGreeting ( STR name )
    RETURN "Hello, " .. name
END FUNCTION

PRINTLN getGreeting ( "Bob" ) // Displays: Hello, Bob

Example: Use in Conditional

FUNCTION isValid ( INT value )
    RETURN ( value >= 0 ) && ( value <= 100 )
END FUNCTION

IF isValid ( 50 )
    PRINTLN "Valid value"
ELSE
    PRINTLN "Invalid value"
END IF
// Displays: Valid value

Example: Pass to Another Function

FUNCTION double ( INT n )
    RETURN n * 2
END FUNCTION

FUNCTION triple ( INT n )
    RETURN n * 3
END FUNCTION

NEW INT value = triple ( double ( 5 ) )
PRINTLN value // Displays: 30

Return Type Consistency

The data type of the returned value must match what the function is expected to return.

Example: Consistent Integer Returns

FUNCTION calculate ( INT x )
    IF x > 0
        RETURN x * 2 // Returns INT
    ELSE
        RETURN 0 // Returns INT
    END IF
END FUNCTION

NEW INT result = calculate ( 5 )
PRINTLN result // Displays: 10

Example: Consistent String Returns

FUNCTION getStatus ( INT code )
    IF code == 200
        RETURN "OK" // Returns STR
    ELIF code == 404
        RETURN "Not Found" // Returns STR
    ELSE
        RETURN "Unknown" // Returns STR
    END IF
END FUNCTION

NEW STR status = getStatus ( 404 )
PRINTLN status // Displays: Not Found

Practical Applications

Example: Temperature Conversion

FUNCTION celsiusToFahrenheit ( FLOAT celsius )
    NEW FLOAT fahrenheit = 0.0
    SET fahrenheit = ( celsius * 9.0 / 5.0 ) + 32.0
    RETURN fahrenheit
END FUNCTION

NEW FLOAT tempC = 25.0
NEW FLOAT tempF = celsiusToFahrenheit ( tempC )
PRINTLN tempC .. " C = " .. tempF .. " F"
// Displays: 25.0 C = 77.0 F

Example: Factorial Calculation

FUNCTION factorial ( INT n )
    IF n <= 1
        RETURN 1
    END IF
    
    NEW INT result = 1
    NEW INT i = 2
    WHILE i <= n
        SET result = result * i
        SET i = i + 1
    END WHILE
    
    RETURN result
END FUNCTION

NEW INT fact5 = factorial ( 5 )
PRINTLN "5! = " .. fact5 // Displays: 5! = 120

Example: Maximum of Three

FUNCTION max ( INT a , INT b )
    IF a > b
        RETURN a
    ELSE
        RETURN b
    END IF
END FUNCTION

FUNCTION maxOfThree ( INT a , INT b , INT c )
    NEW INT maxAB = max ( a , b )
    NEW INT maxABC = max ( maxAB , c )
    RETURN maxABC
END FUNCTION

NEW INT largest = maxOfThree ( 10 , 25 , 15 )
PRINTLN largest // Displays: 25

Example: String Builder

FUNCTION buildReport ( STR title , INT value )
    NEW STR line1 = "=========="
    NEW STR line2 = title
    NEW STR line3 = "Value: " .. value
    NEW STR line4 = "=========="
    RETURN line1 .. line2 .. line3 .. line4
END FUNCTION

NEW STR report = buildReport ( "Sales" , 1000 )
PRINTLN report

Example: Discount Calculation

FUNCTION applyDiscount ( FLOAT price , FLOAT percent )
    IF percent < 0.0
        RETURN price // No negative discounts
    END IF
    
    IF percent > 100.0
        RETURN 0.0 // Max 100% discount
    END IF
    
    NEW FLOAT discount = price * ( percent / 100.0 )
    NEW FLOAT finalPrice = price - discount
    RETURN finalPrice
END FUNCTION

NEW FLOAT price = 100.0
NEW FLOAT salePrice = applyDiscount ( price , 20.0 )
PRINTLN "Sale price: $" .. salePrice
// Displays: Sale price: $80.0

Example: Prime Number Check

FUNCTION isPrime ( INT n )
    IF n <= 1
        RETURN FALSE
    END IF
    
    IF n == 2
        RETURN TRUE
    END IF
    
    IF n % 2 == 0
        RETURN FALSE
    END IF
    
    NEW INT i = 3
    WHILE i * i <= n
        IF n % i == 0
            RETURN FALSE
        END IF
        SET i = i + 2
    END WHILE
    
    RETURN TRUE
END FUNCTION

IF isPrime ( 17 )
    PRINTLN "17 is prime"
ELSE
    PRINTLN "17 is not prime"
END IF
// Displays: 17 is prime

Return with Function Calls

Example: Chaining Function Results

FUNCTION add ( INT a , INT b )
    RETURN a + b
END FUNCTION

FUNCTION multiply ( INT a , INT b )
    RETURN a * b
END FUNCTION

FUNCTION calculate ( INT x )
    NEW INT doubled = multiply ( x , 2 )
    NEW INT increased = add ( doubled , 10 )
    RETURN increased
END FUNCTION

NEW INT result = calculate ( 5 )
PRINTLN result // Displays: 20

Example: Nested Function Returns

FUNCTION square ( INT n )
    RETURN n * n
END FUNCTION

FUNCTION sumOfSquares ( INT a , INT b )
    RETURN square ( a ) + square ( b )
END FUNCTION

NEW INT result = sumOfSquares ( 3 , 4 )
PRINTLN result // Displays: 25

Important Notes

  • Return immediately exits the function and sends a value back to the caller.
  • Code after a Return statement in the same block will not execute.
  • Functions must have at least one Return statement.
  • The returned value's type must match the function's expected return type.
  • Return can send back literals, variables, or expression results.
  • Multiple Return statements can exist in different conditional branches.
  • Return works with all Data Types: Boolean, Integer, Float, and String.
  • When Return executes in a loop, it exits both the loop and the function.
  • Return is only valid inside function definitions.

Common Errors

Error: Missing Return Statement

FUNCTION getValue ( )
    NEW INT x = 10
    // Runtime error! No RETURN statement
END FUNCTION

// Correct:
FUNCTION getValue ( )
    NEW INT x = 10
    RETURN x
END FUNCTION

Error: Return Outside Function

NEW INT x = 10
RETURN x // Syntax error! RETURN only valid in functions

// Correct: Use RETURN only inside functions
FUNCTION getValue ( )
    NEW INT x = 10
    RETURN x
END FUNCTION

Error: Wrong Return Type

FUNCTION getText ( )
    RETURN 42 // Returns INT
END FUNCTION

NEW STR message = getText ( ) // Type error! Cannot assign INT to STR

// Correct:
FUNCTION getText ( )
    RETURN "Hello"
END FUNCTION

NEW STR message = getText ( )

Error: Inconsistent Return Types

FUNCTION process ( INT n )
    IF n > 0
        RETURN "positive" // Returns STR
    ELSE
        RETURN 0 // Returns INT - Type error!
    END IF
END FUNCTION

// Correct: All returns must be same type
FUNCTION process ( INT n )
    IF n > 0
        RETURN "positive"
    ELSE
        RETURN "zero or negative"
    END IF
END FUNCTION

Error: Missing Return in Some Paths

FUNCTION getValue ( INT n )
    IF n > 0
        RETURN n * 2
    END IF
    // Runtime error! No RETURN for n <= 0 case
END FUNCTION

// Correct: All paths must have RETURN
FUNCTION getValue ( INT n )
    IF n > 0
        RETURN n * 2
    ELSE
        RETURN 0
    END IF
END FUNCTION

Error: Return Without Value

FUNCTION calculate ( INT n )
    RETURN // Syntax error! Must return a value
END FUNCTION

// Correct:
FUNCTION calculate ( INT n )
    RETURN n * 2
END FUNCTION

Error: Unreachable Code After Return

FUNCTION test ( )
    RETURN 10
    NEW INT x = 20 // This code never executes
    PRINTLN x // This code never executes
END FUNCTION

// Correct: Don't put code after RETURN
FUNCTION test ( )
    NEW INT x = 20
    PRINTLN x
    RETURN 10
END FUNCTION

Error: Using Returned Value of Wrong Type

FUNCTION getNumber ( )
    RETURN 42
END FUNCTION

NEW STR text = getNumber ( ) // Type error! Cannot assign INT to STR

// Correct: Use matching type
NEW INT number = getNumber ( )

Error: Return in Main Program

NEW INT x = 10
IF x > 5
    RETURN x // Syntax error! RETURN not allowed outside functions
END IF

// Correct: Use EXIT to stop main program
NEW INT x = 10
IF x > 5
    EXIT
END IF

Error: Mixing Return Types

FUNCTION getValue ( BOOL flag )
    IF flag == TRUE
        RETURN 100 // Returns INT
    ELSE
        RETURN 50.5 // Returns FLOAT - Type error!
    END IF
END FUNCTION

// Correct: Keep return type consistent
FUNCTION getValue ( BOOL flag )
    IF flag == TRUE
        RETURN 100.0 // Returns FLOAT
    ELSE
        RETURN 50.5 // Returns FLOAT
    END IF
END FUNCTION