-
Notifications
You must be signed in to change notification settings - Fork 0
Functions
Derek Snider edited this page May 19, 2026
·
1 revision
int add(int a, int b) {
return a + b;
}
void greet(string name) {
cout << "Hello, " << name << endl;
}
int main() {
int result = add(10, 20);
greet("World");
return 0;
}Go-style multiple returns using comma-separated values:
int divmod(int a, int b) {
return a / b, a % b;
}
int main() {
int q, r;
q, r = divmod(17, 5);
cout << "quotient: " << q << ", remainder: " << r << endl;
return 0;
}The := operator also works for multiple returns with type inference:
q, r := divmod(17, 5);Currently works with numeric types only. Always use braces around multi-return
if/elseblocks.
Store a function's address and call through it:
void greet(string name) {
cout << "Hi " << name << endl;
}
int main() {
auto fn = greet;
fn("World"); // calls greet("World")
return 0;
}auto infers the function pointer type from the assigned function.
Anonymous inline functions:
// void lambda
auto print = [](string s) { cout << s << endl; };
// typed-return lambda (return type inside [])
auto add = [int](int a, int b) { return a + b; };
int main() {
print("hello");
int result = add(10, 20);
cout << result << endl; // 30
return 0;
}Return type goes inside []: [int], [string], or [] for void.
Classes support methods with an implicit this pointer:
class Counter {
int count;
void inc() {
count = count + 1;
}
int get() {
return count;
}
};
int main() {
Counter c;
c.count = 0;
c.inc();
c.inc();
cout << c.get() << endl; // 2
return 0;
}See Structs & Classes for more.
int main(int argc, char **argv) {
printf("Script: %s\n", argv[0]);
for (int i = 1; i < argc; i++)
puts(argv[i]);
return 0;
}Run: madc script.mad arg1 arg2 arg3
Both int main() and int main(int argc, char **argv) are supported.
| Function | Description |
|---|---|
puts(s) |
Print C-string + newline |
putchar(c) |
Print a character |
puti(i) |
Print integer |
strlen(str) |
String length |
stoi(str) |
String to integer |
stod(str) |
String to double |
to_string(result, int) |
Integer to string |
system(cmd) |
Run shell command |
getenv(result, name) |
Get environment variable |
setenv(name, value) |
Set environment variable |
Plus all namespace functions and anything available via dlsym (libc functions work automatically).
-
Modern Features — defer,
:=, auto, range-for - Structs & Classes — user-defined types and methods
- Namespaces — 100+ built-in functions from 6 languages
- ← Back to Home