Yasser Mohamed Yasser Mohamed - 1 year ago 120
C Question

Returning more than one variable using c functions

I'm trying to use structure to return more than one variable using following code.

Is there a better way to do this?

and what about this technique, is it efficient?

PS: I'm new to embedded system so trying to discover best techniques for memory , performance and such constrains.

#include <stdio.h>
struct two func(int , int );

struct two {
int x;
int y;


int main() {
printf("values is\n %i\n %i\n ",func(33,44).x,func(33,44).y);
return 0;

struct two func(int x, int y ) {

struct two ex;

return ex;

Answer Source

It's a fine technique, and not inefficient. (But there are also alternatives; one is mentioned in Sean K's answer. See also http://c-faq.com/misc/multretval.html .)

What's inefficient -- and possibly buggy, if the function has side effects -- is to call it twice in order to get its two values. I'd use

struct two r = func(33, 44);
printf("values are %i %i\n", r.x, r.y);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download