C memory managmentBasics
Functions
Functions in C language
Basic example
In C, functions specify the types for their arguments and return value.
float add(int x, int y) {
return (float)(x + y);
}
- The first type,
float
is the return type. add
is the name of the function.int x, int y
are the parameters to the function, and their types are specified.x + y
adds the two arguments together.(float)
casts the result to a float.
Here's the full example:
#include <stdio.h>
float add(int x, int y) {
return (float)(x + y);
}
int main() {
float result = add(10, 5);
printf("result: %f\n", result);
// result: 15.000000
return 0;
}
Void
In C, there's a special type for function signatures: void
. There are two
primary ways you'll use void
:
To explicitly state that a function takes no arguments:
int get_integer(void) {
return 420;
}
When a function doesn't return anything:
void print_integer(int x) {
printf("this is an int: %d", x);
}
It's important to note that void
in C is not like None in Python. It's not a
value that can be assigned to a variable. It's just a way to say that a function
doesn't return anything or doesn't take any arguments.