+ 2
Why we use "void" in functions in C++? explain me plz
I searched on google bt couldn't understand yet. Also why we use return statement in C++
4 Respostas
+ 6
This video will help you. https://youtu.be/9yLSPKsLK0g
+ 3
Function is a block of code, that can be ran by calling its name.
When you call a function it often returns (evaluates) a certain type of value to the position the function was called.
Function can have a header, which specifies what type of values can be returned by the function.
void is a special header which allows you to have functions that won't return values.
You might use void when a function doesn't simply need to return any values.
Return is an obvious statement for function, it is the statement that makes a value to be returned to the position where the function was called.
Return will also terminate function calls.
+ 2
if function does not return to the calling object then we use void
+ 1
Void is used if your function doesn't return anything. Thus, the name is void which means "empty". If you wish to have your function result returned, try int or float or else instead of void.
Example of void function is Swap:
void swap(int *a,int *b){
int temp;
temp=*a;
*a=*b;
*b=temp;
}
in this example, swap doesn't return the swap value. You don't need to prepare a variable to contain the swap result because it wont be returned.
Example of other function with value returned:
int sum(int a,int b){
int sum;
sum=a+b;
return sum;
}
The value of sum is then returned to the variable assigned to it. Remember, you need to have a variable in your main function that holds the result.
Example:
#include <iostream>
using namespace std;
void swap(int *a, int *b){
int temp;
temp=*a;
*a=*b;
*b=temp;
}
int sum(int a, int b){
int sum;
sum=a+b;
return sum;
}
int main() {
int a,b,c;
cin>>a;
cin>>b;
c=sum(a,b);
swap(&a,&b);
cout << a << " " << b << " " << c;
return 0;
}
Input: 1 2
Output : 2 1 3
Hope it helps you :)