Functions in c plus plus
In C++, functions are blocks of code that perform specific tasks and can be called when needed. They help in organizing code, avoiding repetition, and improving readability.
Syntax of a Function in C++
return_type function_name(parameter_list) {
// body of the function
// return statement (if needed)
}
Example: Simple Function
#include<iostream>
using namespace std;
void greet() {
cout << “Hello, welcome to C++!” << endl;
}
int main() {
greet(); // function call
return 0;
}
Note:output of above code will be a message ” Hello, welcome to C++”.
A brief explanation of the difference between void and return-type functions in C++:
1.Void Function
- ‘void’ keyword shows that the function does not return a value.
- It is used when you just want to perform an action (like printing).
- Example:
void greet() {
cout << "Hello!" << endl;
}
2.Return-Type Function
- when a function returns a value using the
'return'
keyword in the end of body of function and ‘int’ / ‘double’ etc keywords are used in place of ‘void’ such functions fall under category of return type. - It is useful when you need to get a result back from the function.
int add(int a, int b) {
return a + b;
}
Types of Functions
- User-defined functions – created by the programmer.
- Standard library functions – built-in like
sqrt()
,pow()
, etc.
Problems :