Mastering C Textbook
Function Mastery
A function in C is a block of code that does a specific job. Each function has a few key parts:
Return Type: This tells you what type of value the function will give back. If it doesn’t return anything, it will use the keyword void
Function Name: This is the function’s name, which you use to call it in your code. The name should describe what the function does. For example, you can create a function called printHello that prints “Hello” to the console.
Parameters: These are optional values you can pass to a function when you call it. They help the function perform its job. If your function doesn’t need extra data, you can create it without parameters. To add a parameter, include it when defining the function, like this: void printNumber(int num), which takes in a number to print.
Body: The block of code inside { } that contains the instructions the function runs when it’s called.
Return Statement: Sends a value back from the function to where it was called. If the return type is void, this statement is optional. Otherwise, it must return a value that matches the function's return type.
Prototypes
These are function prototypes. A prototype in C acts like a preview of a function. It tells the compiler the function's name, what it returns, and what parameters it needs. This helps the compiler know how to use the function before it sees the full code. Prototypes are usually placed at the top of your code or in a header file.
To use functions in your main file where your main function is, you need to either prototype them or write them completely above your main function; otherwise, your program will not recognize them when running your code.
Keep reading this lesson
You've reached the end of the free preview. Unlock the rest of this lesson plus 11 more lessons in Mastering C Textbook.
- Unlimited coding questions
- Unlimited access to all classroom material
- Weekly live call for questions and guidance
- 3,000 AI tutor tokens / month
- Personal SQL database (3 MB)
- Progress tracking
Cancel any time.