Procedures in PascalABC.NET

What are procedures?

A procedure is an independent sequence of statements that can be called multiple times from different parts of the program. It allows structuring code into smaller blocks, making it easier to understand and maintain.

Argumentless Procedures

An argumentless procedure does not accept any input values (arguments), but performs specific operations internally when invoked.

        procedure SayHello;
begin
  println('Hello, World!'); // Output string on screen
end;

The SayHello procedure simply outputs the message "Hello, World!".

More Advanced Example:

        procedure DrawRectangle;
begin
  for var i := 1 to 5 do begin
    for var j := 1 to 10 do print('*');
    println;
  end;
end;
begin
  DrawRectangle; // Call the rectangle-drawing procedure
  readln; // Wait for user key press
end.

This program clears the screen, calls the DrawRectangle procedure which draws a 5×10 rectangle made up of asterisks (*) on the screen, and waits for the user to press Enter before exiting.

Procedures with Arguments

When working with procedures, it's often necessary to pass additional data—known as arguments—to them. There are two ways to pass arguments:

  • By value: A copy of the variable is passed, so changes inside the procedure don’t affect the original outside.
  • By reference: The memory address of the variable is passed, meaning any modifications within the procedure directly change the original variable.

Passing Arguments by Value

        procedure DoubleValue(x: integer);
begin
  x := x * 2; // Doubling the local copy of the variable
  println('Inside procedure:', x); // Outputs doubled value
end;

begin
var num: integer = 5;

   println('Original value:', num); // Original value remains unchanged
   DoubleValue(num); // Execute the doubling procedure
   println('After calling procedure:', num); // Still the same because passed by value
end.

We pass a variable num to the procedure DoubleValue. Inside the procedure, its value gets doubled, but this affects only the local copy, leaving the external variable unchanged.

Passing Arguments by Reference

        procedure SquareNumber(var x: integer);
begin
  x := x * x; // Directly squaring the number
  println('Squared number:', x); // Reflects immediate change
end; begin
var  number: integer = 7;   println('Initial value:', number); // Initial value: 7
   SquareNumber(number); // Calculate square
  println('Final value after call:', number); // Now shows squared value (49)
end.

Using the var keyword ensures that the modification inside the procedure alters the global variable.

Conclusion

Using procedures helps structure programs into logical blocks, simplifying understanding and maintaining large projects. Deciding how to pass arguments (by value vs. by reference) depends on what behavior you're aiming for.