Thread: value-returning functions

  1. #1
    Registered User
    Join Date
    Oct 2002
    Posts
    33

    value-returning functions

    Is it possible for them to return more than one value without using any advanced tools.

    I tried to do it in this code, but only one value in the function was printed:

    Code:
    #include<iostream>
    
    int main()
    {
    
        float function(float,float);
        
        float a=3.4,b=7.8;
        cout<<a<<endl<<b<<endl;
        cout<<function(a,b);
        
        return 0;
    }
        
    float function(float a,float b)
    {
     a=32.2;
     b=90.2;
     return a;
     return b; // I also tried "return a,b;" with no success
    }

  2. #2
    Just a Member ammar's Avatar
    Join Date
    Jun 2002
    Posts
    953
    Using the key word return, you can only return one variable.
    If you want to modify many variables, just pass them by reference.
    none...

  3. #3
    Registered User
    Join Date
    Dec 2002
    Posts
    119
    A function can only return one value. To get around this restriction you have two options:
    1) Return a struct or class that contains more than one value
    2) Pass variable to the function by reference, meaning the function can change the value of the variables, but they are the same variables that were passed in and can be accessed again after the function call.
    Code:
    #include<iostream>
    struct numbers{
      float a;
      float b;
      float c;
    };
    numbers dummyFunct(numbers nums)
    {
      nums.a = 92.3;
      nums.b = 77.654;
      nums.c = 0.99;
      return (nums);
    }void funct(float &a, float &b)
    {
        a = 5.4;
        b = 87.45;
    }
    int main()
    {
        numbers someNums;
        someNums.a = 3.4;
        someNums.b = 7.8;
        someNums.c = 99.5;
           cout<<someNums.a<<endl<<someNums.b<<endl<<coutsomeNums.c<<endl;
       dummyFunct(someNums);
    cout<<someNums.a<<endl<<someNums.b<<endl<<coutsomeNums.c<<endl;
        
    float   one=987.34, two=0.876;
    cout << one << "  " << two << endl;
    funct(one, two);
    cout << one << "  " << two << endl;
        return 0;
    }
    Hope that helps
    -Futura

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 3
    Last Post: 05-12-2009, 06:17 AM
  2. An array of macro functions?
    By someprogr in forum C Programming
    Replies: 6
    Last Post: 01-28-2009, 07:05 PM
  3. Replies: 7
    Last Post: 11-17-2008, 01:00 PM
  4. Passing pointers between functions
    By heygirls_uk in forum C Programming
    Replies: 5
    Last Post: 01-09-2004, 06:58 PM
  5. Class accessor functions returning strings?
    By Shadow12345 in forum C++ Programming
    Replies: 6
    Last Post: 12-31-2001, 12:48 PM