Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return two values in C

Tags:

c

I have the following function:

int conMS(time_in_seconds) {
  int minutes, seconds;
  minutes = time_in_seconds / 60;
  seconds = time_in_seconds % 60;
  return minutes, seconds;
}

When used in another function, I get several error messages:

warning: left-hand operand of comma expression has no effect [-Wunused-value]
warning: left-hand operand of comma expression has no effect [-Wunused-value]
 minutes,seconds = conMS(time);
warning: ‘minutes’ is used uninitialized in this function [-Wuninitialized]
warning: left-hand operand of comma expression has no effect [-Wunused-value]
 return minutes, seconds;

Anyways, is there a way where one can return two values from a function. Those two values could by anything: an int and a char, a float and an int...

I'm sorry if this is a no-brainer for you,but I'm a beginner in C and the only way I can learn is by asking questions. Also please make your explanation as simple as possible.

Update: This can be easily done through pointers as follow.

void conMS(int time, 
int *minutesP, /* a pointer to variable minutes */
int *secondsP) // a pointer to variable seconds //
{ 
    *minutesP = time / 60; 
    *secondsP = time % 60; 
}   

Later on you would call this function as:

conMS( 210, &minutes, &secs)    /* Where minutes, secs are defined integers */ 

And this would assign the time in seconds to the variable minutes and assign seconds to the variable secs

like image 661
Andy_A̷n̷d̷y̷ Avatar asked Dec 30 '13 10:12

Andy_A̷n̷d̷y̷


Video Answer


2 Answers

Two choices:

1) Pass pointers to the variables that will be modified. Your function prototype then becomes

int conMS(time_in_seconds, int* minutes, int* seconds)

2) Use a struct containing minutes and seconds as members and return that.

I prefer (1) as in the case of (2) I'm always anxious about taking unnecessary value copies and I get nervous when relying on return value optimisation as that's essentially a compiler choice and not mandated by standard C. Also, the caller syntax comMS(time_in_seconds, &minutes, &seconds) tells me to expect minutes and seconds to be modified.

Some convention has also grown with option (1): a zero result normally indicates success, non-zero for failure.

like image 121
Bathsheba Avatar answered Oct 01 '22 15:10

Bathsheba


You can create struct and return it

struct time{
   int minutes;
   int seconds;
};

struct time conMS(time_in_seconds)
{
   struct time ret;
   ret.minutes = time_in_seconds / 60;
   ret.seconds = time_in_seconds % 60;
   return ret;
}
like image 23
dzielins42 Avatar answered Oct 01 '22 13:10

dzielins42