Functions in A++
Functions are reusable blocks of code that perform specific tasks. A++ provides a rich set of features for working with functions.
Function Basics
Function Declaration
c++
// Basic function
#define yield_type function_name(parameter_type parameter) {
// function body
yield value;
}
// Example
#define int add(int a, int b) {
yield a + b;
}
Function Types
c++
// Nothing function (no return value)
#define nothing greet(string name) {
print("Hello, " + name + "!");
}
// Function with return value
#define int multiply(int x, int y) {
yield x * y;
}
// Function with multiple parameters
#define string formatName(string firstName, string lastName) {
yield firstName + " " + lastName;
}
Advanced Function Features
Recursion
c++
// Recursive factorial function
#define int factorial(int n) {
if (n <= 1) {
yield 1;
}
yield n * factorial(n - 1);
}
print("Factorial of 5: " + factorial(5)); //Ouput: factorial of 5: 120
Best Practices
- Single Responsibility
c++
// Bad: Function does too much
#define nothing processUser(User user) {
validateUser(user);
saveToDatabase(user);
sendEmail(user);
}
// Good: Separate concerns
#define nothing validateUser(User user) { ... }
#define nothing saveUser(User user) { ... }
#define nothing notifyUser(User user) { ... }
- Descriptive Names
c++
// Bad
#define nothing p(string s) { ... }
// Good
#define nothing printMessage(string message) { ... }
- Parameter Validation
c++
#define int calculateArea(int width, int height) {
if (width <= 0 || height <= 0) {
print("Dimensions must be positive");
yield 0;
}
yield width * height;
}
- Yield Early Pattern
c++
#define boolean validateUser(User user) {
if (!user.name) yield nope;
if (!user.email) yield nope;
if (user.age < 18) yield nope;
yield yup;
}
Next Steps
- Learn about Classes and Objects
- Explore Error Handling
- Study Advanced Topics