can a function return 2 values?

This is a discussion on can a function return 2 values? within the C Programming forums, part of the General Programming Boards category; ok, I'm use to making functions that return one value, where I usually just write someting like: return ( something ...

  1. #1
    Registered User
    Join Date
    Sep 2005
    Posts
    84

    can a function return 2 values?

    ok, I'm use to making functions that return one value, where I usually just write someting like:

    return ( something ) ;

    and I get a value for my preceeding funciton.

    but right now I am trying to write a function that takes no inputs
    but brings back 2 values to its preceeding function. I've been trying things like:

    return ( x = something, y = something ) ;

    but it doesnt work. i have the x and y variables in the preceeding fucntion, i've tried different variations of it but can't get it to work.

    does anyone know how to make a function return 2 values to two differnent variable in your main funciton?

    thank you

  2. #2
    J0n
    J0n is offline
    Registered User
    Join Date
    Sep 2005
    Posts
    1
    You cannot 'return' multiple values, but you can instead pass pointers to the variables to your function. e.g.

    Code:
    void
    f(int *x, int *y)
    {
        x = 1;
        y = 2;
    }
    int
    main(void)
    {
        int a, b;
        f(&a, &b);
        return 0;
    }
    If however, you want your function to take no inputs, you could return a struct containg multiple fields. Or, you could make the variables public.
    Last edited by J0n; 09-27-2005 at 03:33 AM.

  3. #3
    & the hat of GPL slaying Thantos's Avatar
    Join Date
    Sep 2001
    Posts
    5,681
    functions in C are basically defined like they are in math. You can give it multiple inputs but you still only get one output. Now there are lots of tricks to get around this, such as passing the variables as a pointer or returning a structure that contains the information

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 4
    Last Post: 05-13-2011, 09:28 AM
  2. Seg Fault in Compare Function
    By tytelizgal in forum C Programming
    Replies: 1
    Last Post: 10-25-2008, 04:06 PM
  3. Smart pointer class
    By Elysia in forum C++ Programming
    Replies: 63
    Last Post: 11-03-2007, 08:05 AM
  4. <Gulp>
    By kryptkat in forum Windows Programming
    Replies: 7
    Last Post: 01-14-2006, 01:03 PM
  5. Contest Results - May 27, 2002
    By ygfperson in forum A Brief History of Cprogramming.com
    Replies: 18
    Last Post: 06-18-2002, 02:27 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21