Functions with return type returning no values
An interesting thing about a functions in C++ with a non-void return type is that if you forget to place a return statement at the end of your function the it automatically return the ""result of last arithmetic operation"" done in that function code or else a 0 in normal functions and a garbage value if the function is inside a class
For eg-:
#include <iostream>
#include<conio.h>
using namespace std;
int fun()
{
int i = 34 ;
int j = i + 1 ; //no return type mentioned here still output is 35
}
int main()
{
cout << fun(); //output is 35
getch();
return 0;
}
another example where the line j = i + 1 is missing
#include <iostream>
#include<conio.h>
using namespace std;
int fun()
{
int i = 34 ;
// int j = i + 1 ;
}
int main()
{
cout << fun(); // output is 0
getch();
return 0;
}
For eg-:
#include <iostream>
#include<conio.h>
using namespace std;
int fun()
{
int i = 34 ;
int j = i + 1 ; //no return type mentioned here still output is 35
}
int main()
{
cout << fun(); //output is 35
getch();
return 0;
}
another example where the line j = i + 1 is missing
#include <iostream>
#include<conio.h>
using namespace std;
int fun()
{
int i = 34 ;
// int j = i + 1 ;
}
int main()
{
cout << fun(); // output is 0
getch();
return 0;
}
Nice bro keep it up..;)
ReplyDeletehey what if data type is void than what value will it return if we apply with printf or cout function. like void fun(){int j=1;j=j+1}
ReplyDeletethan in main() function cout<<fun();
--Shubham
writing cout<<fun(); in main() will generate an error bcoz a void function returns nothing and therefore cout will get no value to be displayed therefore an error
Delete