Mastering C++
Intro To Functions
Understand FunctionsA function in C++ is a block of code that performs a specific job. Each function has several key parts:
Return Type: This tells you what kind of value the function will give back. If it doesn’t return anything, it will use the keyword
void.Function Name: This is the name you use when you want to call the function. It should describe what the function does.
Parameters: These are optional inputs you can send into a function to help it do its job. If the function doesn’t need extra data, you can leave the parentheses empty.
Body: This is the block of code inside
{ }that runs when the function is called.Return Statement: This sends a value back to wherever the function was called. If the return type is
void, you don’t need a return statement. Otherwise, you must return a value that matches the return type.
A – Declaring and Calling Functions
When writing a program in C++, you can create your own functions to do different jobs. But one important rule is this: You must tell the compiler about a function before you use it.
The compiler reads your code from top to bottom. So if you call a function before the compiler has seen how that function works (its definition), it won’t know what to do and will give you an error.
To fix this, you have two options:
Option 1: Define the Function Before You Use It
This means writing the full function code above main() or above wherever you call it.
#include <iostream>
using namespace std;
// Full definition before main
void greet() {
cout << "Hello!" << endl;
}
int main() {
greet(); // This works because the compiler already saw greet()
return 0;
}Option 2: Use a Function Prototype
If you don’t want to write the full function at the top, you can give the compiler a preview called a function prototype. A prototype only includes:
Keep reading this lesson
You've reached the end of the free preview. Unlock the rest of this lesson plus 21 more lessons in Mastering C++.
- 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.