Published by Patrick Mutisya · 14 days ago
In structured programming, a procedure (or function) is a self‑contained block of code that can be called from other parts of a program. Parameters allow data to be passed into and out of these procedures, making code reusable and easier to understand.
Two main mechanisms are used in most languages:
When a procedure is called, the value of each argument is copied into a new local variable (the parameter). Modifications to the parameter do not affect the original argument.
Example (Python‑like pseudocode):
def increment(x):
x = x + 1 # modifies only the local copy
return x
a = 5
b = increment(a) # a remains 5, b becomes 6
The procedure receives a reference to the original variable. Any change to the parameter directly alters the caller’s variable.
Example (C++‑like pseudocode):
void double \cdot alue(int &n) { // & indicates reference
n = n * 2; // modifies the original variable
}
int a = 4;
double \cdot alue(a); // a becomes 8
Many languages allow parameters to have default values, which are used if the caller omits that argument.
Example (Python):
def greet(name, greeting="Hello"):
print(greeting + ", " + name + "!")
greet("Alice") # uses default greeting: "Hello, Alice!"
greet("Bob", "Hi") # overrides default: "Hi, Bob!"
Parameters are local to the procedure in which they are declared. Their lifetime begins when the procedure is entered and ends when it returns.
| Feature | Call‑by‑Value | Call‑by‑Reference | Default Parameters |
|---|---|---|---|
| What is passed? | Copy of the argument’s value | Reference (address) to the original variable | Specified value used when argument omitted |
| Effect on caller’s variable | Unaffected | Modified if parameter is changed | None – only supplies a value |
| Memory usage | Extra copy created | No extra copy (reference only) | Same as normal parameters |
| Typical language support | Python, Java (primitive types), C | C++, Java (objects), Pascal (var parameters) | Python, C++, Java (overloaded methods) |
proc foo(a: int, b: int ref).The following pseudocode demonstrates a simple bubble‑sort procedure that sorts a list passed by reference.
proc bubbleSort(arr: list ref):
n = length(arr)
repeat
swapped = false
for i = 1 to n-1 do
if arr[i] > arr[i+1] then
temp = arr[i]
arr[i] = arr[i+1]
arr[i+1] = temp
swapped = true
end if
end for
n = n - 1
until not swapped
end proc
# Main program
myList = [5, 2, 9, 1, 6]
bubbleSort(myList) # myList is sorted in‑place