Core Features
Functions
Wrap your code!
To make a specific block of code reusable, you can wrap it inside a function. In cambo, functions can take inputs (parameters), process data and optionally return a result.
syntax
type identifier(parameters){
# code ...
}
typecan any, void, primitive types, or user-defined types, pointers, etc.parametersis optional, can be none, one or more.mainfunction is another story for this, see
Example:
int add(int a, int b){
return a + b;
}
void do_nothing(){
return;
}
int main(string args[]){
do_nothing();
int result = add(1, 2);
return 0;
}
A value must be returned from a function, except the return type is
void.Default value parameters
syntax
type identifier(type identifier = value){
}
- Default value must be constant, which is known at compile time.
- A parameter with default value will become optional, can be skipped when the function is called
- All default value parameters should be defined at the end of parameter list
Example:
float scale(float a, float factor = 1.0){
return a * factor;
}
int main(string args[]){
float r1 = scale(3.0); # r1 = 3.0 * 1.0 = 3.0
float r2 = scale(3.0, 1.5); # r2 = 3.0 * 1.5 = 4.5
return 0;
}
However, in some cases, assume you have 2 default-valued parameters (or more), and you want to keep the first one stays default but the change the last, you can use the default keyword.
Example:
void print_text(string text, float opacity = 1.0, int size = 12){
# implementation ...
}
int main(string args[]){
print_text("hello, world!", default, 15);
return 0;
}
With
default keyword, you don't need to know the exact default value of opacity, the compiler will take of it.