Overview of Functions

Functions are reusable blocks of code that perform specific tasks. They help you organize your code, improve readability, and promote code reuse.

Defining Functions

To define a function in Carbon, you use the func keyword followed by the function name, a list of parameters (if any), and a return type.

Code snippet

func greet(name: string) -> string {
  return "Hello, \(name)!"
}

Calling Functions

To call a function, you provide the function name and any necessary arguments.

Code snippet

var message: string = greet("Alice");
print(message);

Parameters and Return Values

Functions can take parameters as input and return a value as output. Parameters are variables that are passed to the function when it is called. The return type specifies the type of value the function will return.

Example:

Code snippet

func add(a: int, b: int) -> int {
  return a + b;
}

var sum: int = add(3, 5);
print(sum);

Function Overloading

Carbon supports function overloading, which allows you to have multiple functions with the same name but different parameters.

Code snippet

func greet() -> string {
  return "Hello!"
}

func greet(name: string) -> string {
  return "Hello, \(name)!"
}

Recursive Functions

Functions can call themselves recursively, which can be useful for solving problems that can be broken down into smaller, similar subproblems.

Code snippet

func factorial(n: int) -> int {
  if n == 0 {
    return 1;
  } else {
    return n * factorial(n - 1);
  }
}

Anonymous Functions

Carbon also supports anonymous functions, which are functions without a name. They are often used as closures or callback functions.

Code snippet

var greet: () -> string = {
  return "Hello!";
}

var message: string = greet();
print(message);

Functions are a fundamental building block of Carbon programs. By using functions effectively, you can improve code organization, readability, and maintainability.

Iteration Control Structures
Introduction to Object-Oriented Programming (OOP)

Get industry recognized certification – Contact us

keyboard_arrow_up
Open chat
Need help?
Hello 👋
Can we help you?