Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to return two values in C
    text
    copied!<p>I have the following function:</p> <pre><code>int conMS(time_in_seconds) { int minutes, seconds; minutes = time_in_seconds / 60; seconds = time_in_seconds % 60; return minutes, seconds; } </code></pre> <p>When used in another function, I get several error messages:</p> <pre><code>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; </code></pre> <p>Anyways, is there a way where one can return two values from a function. Those two values could by anything: an <code>int</code> and a <code>char</code>, a <code>float</code> and an <code>int</code>...</p> <p>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. </p> <p><strong>Update:</strong> This can be easily done through pointers as follow. <br></p> <pre><code>void conMS(int time, int *minutesP, /* a pointer to variable minutes */ int *secondsP) // a pointer to variable seconds // { *minutesP = time / 60; *secondsP = time % 60; } </code></pre> <p>Later on you would call this function as: </p> <pre><code>conMS( 210, &amp;minutes, &amp;secs) /* Where minutes, secs are defined integers */ </code></pre> <p>And this would assign the time in seconds to the variable <code>minutes</code> and assign seconds to the variable <code>secs</code></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload