Function Basics
Defining and calling functions
Interview Relevant: Fundamental concept
Function Basics
Functions are reusable blocks of code that perform specific tasks.
Function Components
- Return type: Type of value returned
- Name: Identifier to call the function
- Parameters: Input values
- Body: Code to execute
Code Examples
Basic function declaration, definition, and calling.
cpp
1// Function declaration (prototype)
2int add(int a, int b);
3
4// Function definition
5int add(int a, int b) {
6 return a + b;
7}
8
9// Function with no return value
10void greet(const string& name) {
11 cout << "Hello, " << name << "!" << endl;
12}
13
14// Function with no parameters
15int getRandomNumber() {
16 return rand() % 100;
17}
18
19// Main function - entry point
20int main() {
21 int result = add(5, 3); // Call function
22 greet("Alice");
23 cout << "Random: " << getRandomNumber() << endl;
24 return 0;
25}