Regarding returning of function

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • avinash jain
    New Member
    • Aug 2007
    • 12

    Regarding returning of function

    hi guys .. could any one tell which one is bette..

    code1:


    result add ( int a , int b )
    {
    return ( a+b) ;
    }


    code 2:
    void add ( int a , int b , int result)
    {
    result = a+b ;
    return result;
    }

    which one is better whether the code1 or code 2

    Dont consider about the temp variable.. what I need whether its better to use the return statement or in the parameters itself we could pass the reference..
  • rhitam30111985
    New Member
    • Aug 2007
    • 112

    #2
    code 2 is wrong .. void function cant return value.. if retuRn value was int .. it wudnt make a difference except for the fact that extra memory wud be used for the result variable.. however if u have to use void as a return value, u can make use of reference parameter:

    [CODE=cpp]
    void add(int a,int b, int &result)
    {
    ...//omit the return statement
    }
    [/CODE]

    Comment

    • weaknessforcats
      Recognized Expert Expert
      • Mar 2007
      • 9214

      #3
      You use this form:
      Originally posted by avinash jain
      result add ( int a , int b )
      {
      return ( a+b) ;
      }
      when you want to use the function on the right side of an assignment operator:
      [code=cpp]
      int result = add(3,4);
      [/code]

      You use this form:
      Originally posted by avinash jain

      void add ( int a , int b , int result)
      {
      result = a+b ;
      return result;
      }
      when you want to use the return type as an error/success value:

      [code=cpp]
      enum PassCode {SUCCESS, FAIL, NULL_POINTER, etc...}
      PassCode add ( int a , int b , int& result)
      {
      result = a+b ;
      return SUCCESS;
      }
      [/code]

      In any case do not time share the return with results and error codes. Too often the caller doesn't check the return value and starts using your error code as the result.

      Comment

      Working...