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;
}






About the author

Admin
Donec non enim in turpis pulvinar facilisis. Ut felis. Praesent dapibus, neque id cursus faucibus. Aenean fermentum, eget tincidunt.

3 comments:

  1. hey 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}
    than in main() function cout<<fun();
    --Shubham

    ReplyDelete
    Replies
    1. 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

Template by Clairvo Yance
Copyright © 2012 Enigma of IT and Blogger Themes.