0

I have been searching for the answer for this for about an hour and I am very new to C. I am getting the warning "left-hand operand of comma expression has no affect" when referring to this line

return studio, one, two;

The statement is not returning variables one or two to my knowledge from what my print function is showing. Is this the correct way to return multiple variables in C or am I doing it wrong? This is the first time I have had to do this and we didn't discuss this in my class. Apologizes in advance for (I'm sure) a very simple fix.

3 Answers3

3

You can't return multiple values in C. Your options are to return a struct, or to pass in references to the variables you want to modify:

Return struct:

struct studio_stuff {
   int studio;
   int one;
   int two;
};

struct studio_stuff foo()
{
   struct studio_stuff ret;
   ret.studio = 0;
   ret.one = 1;
   ret.two = 2;
   return ret;
}

Pass in references to modify:

void foo(int * studio, int * one, int * two)
{
    *studio = 0;
    *one = 1;
    *two = 2;
}
Gillespie
  • 5,780
  • 3
  • 32
  • 54
2

You cannot return multiple values in C. You can achieve a similar (though not identical) effect by one of:

  • returning a structure or (pointer to a conceptual) array.
  • writing to multiple pointers passed as parameters
Michael Rawson
  • 1,905
  • 1
  • 15
  • 25
  • 1
    Note that you can't return an actual array. – Quentin Feb 02 '15 at 23:46
  • Note that if you return a pointer to an array, you have to worry about memory allocation. Embedding the array in a structure avoids that problem, but reduces to the first alternative (return a structure). On the whole, return a structure or multiple pointer arguments are the best choices. – Jonathan Leffler Feb 02 '15 at 23:50
2

The comma operator evaluates its first operand, discards the result, and gives the result of the second.

So return studio, one, two will evaluate studio, discard the value, evaluate one, discard the value, evaluate two and return that value.

There is no way to return multiple values from a function. The options are to return a struct (the value of a struct is composed of a set of values) or pass additional arguments that are pointers. For example;

struct X func();

works because struct X can contain multiple values.

Alternatively

int func(double *y);

is a function that can return an int, or set the value of *y (which will be visible to the caller).

Rob
  • 1,966
  • 9
  • 13