In C++, a function is a block of code that performs a specific task. It allows you to write code once and reuse it wherever needed, helping to make the program more modular and organized.
A function is a group of statements that is executed when it is called from some point of the program.
Syntax:
return_type function_name(parameters) {
// Function body
return value; // Return statement (if needed)
}
Explanation:
1. Return Type: Specifies the type of value the function will return (e.g., int, float, void for no return).
2. Function Name: A unique identifier for the function (e.g., addNumbers, printMessage).
3. Parameters (Optional): Inputs to the function that allow it to process data. These are written inside parentheses after the function name.
4. Body: The block of code that defines what the function does, enclosed in curly braces { }.
Example:
#include <iostream>
using namespace std;
// define the function
void display() {
cout << "Hello, World!" << endl;
}
int main() {
display(); // Function call
return 0;
}
Output:
Explanation:
1. Return type: void (no return value)
2. Function name: display
3. Parameters: None
4. Body: Prints a message
C++ Function – Questions and Answers
Q 1: What is a function in C++?
Ans: A block of code that performs a specific task.
Q 2: Why use functions?
Ans: For code reusability and modularity.
Q 3: What are function components?
Ans: Function name, return type, parameters, and body.
Q 4: How do you call a function?
Ans: By using its name followed by parentheses.
Q 5: Can a function return multiple values?
Ans: Yes, using structures or references.
C++ function – Objective Questions (MCQs)
Q1. What is the correct syntax to declare a function in C++?
Q2. Which of the following is TRUE about C++ functions?
Q3. What is the return type of a function that does not return any value?
Q4. How do you call a function named display in C++?
Q5. Which part of the function defines its functionality?