Course Content
C Basics
C Basics
Void, Recursion
The void Return Type in C
In the C programming language, functions that are declared with a specific return type are expected to have a return statement, delivering a value matching that type. However, there are scenarios where a function doesn't need to return anything – perhaps it's simply displaying text on the screen. For such instances, the function should be declared with the void
type.
Main
#include <stdio.h> void func() { printf("This function returns nothing\n"); } int main() { func(); return 0; }
The void
keyword specifies that a function doesn't return a value, and it can also be used in the context of pointers. Attempting to declare a variable of type void
will result in an error because the compiler won't understand how much memory to allocate.
Here's an intentional error for illustration.
Main
#include <stdio.h> int main() { void variable; return 0; }
Delving into Recursion
C supports the ability for a function to call itself, a technique known as recursion.
Imagine recursion as the action of stretching and then releasing a rubber band. It's commonly leveraged in mathematical operations, such as calculating factorials.
For instance: 3! = 3 x 2 x 1
Factorials are often utilized in approximating function values by expanding these functions into Taylor or Maclaurin series.
Note
This chapter's inspiration came right after the author completed a lab assignment at a university. The task was to approximate the cotangent value to a certain precision by expanding it into a Taylor series. And naturally, the factorial computation was indispensable.
Main
#include <stdio.h> int factorial(int n) { // if n = 0 or 1, because 0! = 1 and 1! = 1 if (n == 0 || n == 1) return 1; // recursion case else return n * factorial(n - 1); } int main() { int n = 3; printf("factorial(%d) = %d\n", n, factorial(n)); return 0; }
In the context of recursion, the function will continue to call itself until it meets the condition n == 0 || n == 1
. Once this condition is satisfied, the results from the subsequent factorial()
function calls are returned in the reverse order, similar to folding an accordion. By the time step 6 is reached, the initial call to factorial(3)
will return 6
.
Thanks for your feedback!