Problem scenario
You are familiar with functions in programming languages (e.g., Python or SQL). You like how you can create a modular program with a function. Functions can allow you to reuse code and do data processing in a way that is readable. Logic can be created rapidly when you know how to use a function. How do you write a function in the C?
Solution
Prerequisites
Install the C compiler. If you need directions, see this posting.
Procedures
Use this example. The function here is called "printer".
1. Create a file called funcexample.cc.
2. Put the following lines in it (starting with "/* function example */" and ending with the last "}").
/* function example */
#include <stdio.h>
#include <string.h>
int printer(int z) {
printf ("found %s\n","a test");
z = z + 1;
return z;
}
int main ()
{
int y;
y = printer(3);
printf ("y is a %d\n",y);
return 0;
}
3. Compile the code with gcc funcexample.cc.
4. Run it like this: ./a.out
You should see that y was assigned via the "printer" function. Remember that "printer" is not a reserved word. It is a function that returns an integer based on the way it was defined above.