C language subfunction is a reusable block in the program, which can be called by the function name to avoid writing the same code repeatedly and improve the readability and maintainability. The following describes how to write C subfunctions.
1. Define the function.
In C, functions are defined using the "void" keyword, followed by parentheses and a type identifier, for example:
cvoid print_hello()
printf("hello, world!");
What this function does is output "hello, world!".string.
2. Call the function.
In the main program, subfunctions can be called by their names, for example:
cint main()
print_hello();Call the print hello function.
return 0;
In the example above, the main function calls the print hello function and outputs "hello, world!".string.
3. Parameter transfer.
If a subfunction needs to accept parameters, you can add a list of parameters in parentheses when defining the function, for example:
cint add(int a, int b) {
return a + b;
The purpose of this function is to implement the addition of two integers. When the function is called, you need to pass arguments to the function, for example:
cint main()
int result = add(2, 3);Call the add function, passing parameters 2 and 3
printf("result: %d", result);Output 5
return 0;
In the example above, the main function calls the add function, passing two arguments 2 and 3, the add function returns the sum of the two numbers, and finally the main function outputs the result 5.
4. Return value type and return value.
In C, each function has a return value type and a return value. If the function doesn't need to return any value, you can use "void" as the return value type. If the function needs to return a value, you need to specify the return value type when the function is defined, and use the "return" keyword at the end of the function to return a value. For example:
cint add(int a, int b) {
return a + b;Returns the sum of two integers.
In the example above, the return value of the add function is of type "int", and the return value is the sum of two integers. When the function is called, the return value can be assigned to a variable, for example:
cint main()
int result = add(2, 3);Call the add function and assign the return value to the variable result
printf("result: %d", result);Output 5
return 0;