Skip to content

Functions

Derek Snider edited this page May 19, 2026 · 1 revision

Functions

Basic functions

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;
}

Multiple return values

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/else blocks.

Function pointers

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.

Lambda expressions

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.

Class methods

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.

Command-line arguments

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.

Built-in functions

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).

What's next?

Clone this wiki locally