Functions are like magical spells that perform specific tasks. Let’s start casting some spells!
Defining Functions
Functions are sets of instructions that perform a specific task. They help us break our code into smaller, manageable pieces.
fn greet() void {
std.debug.print("Hello, adventurer!\n", .{});
}
Imagine you have a special power. What would your power be, and what kind of instructions would you give to use it?
Function Parameters and Return Values
Parameters are like inputs for a function. They allow us to customize what the function does.
fn greet(name: []const u8) void {
std.debug.print("Hello, {}, the brave!\n", .{name});
}
Return Values are what the function gives back once it’s done its job.
fn multiply(a: i32, b: i32) i32 {
return a * b;
}
If you were a master chef, what ingredients would you need (parameters), and what dish would you serve (return value)?
Procedures
Procedures are functions that don’t return anything. They’re like tasks that need to be done, but they don’t give back a specific result.
pub fn prepareSoup() void {
// Code for preparing soup goes here.
}
Imagine you’re in charge of preparing a grand feast. What tasks (procedures) would you need to complete?
Function Overloading
Function Overloading allows us to have multiple functions with the same name but different parameters.
fn greet(name: []const u8) void {
std.debug.print("Hello, {}, the brave!\n", .{name});
}
fn greet(name: []const u8, title: []const u8) void {
std.debug.print("Greetings, {}, the {}. Welcome!\n", .{name, title});
}
If you were a master of disguise, how would you use function overloading to take on different roles?
Need further assistance, paid dedicated one-to-one tutor, need assignments done or have a paid project in Zig?
Leave a Reply