0
struct r() {
    return 1, "hello";
}

int main() {

    int x;
    char y[100];
    x, y = r(); // set x to int 1, and set y to "hello"

}

Is there anyway I can do this ? I believe this is possible in C

e t
  • 243
  • 2
  • 11
  • Well, certainly not like that. I would suggest. I would suggest finding a book from this list - https://stackoverflow.com/questions/562303/the-definitive-c-book-guide-and-list – OldProgrammer Mar 02 '18 at 02:55

3 Answers3

3

A function cannot return multiple values.

You can however pass pointers so that a function writes the data through the pointer:

void foo(int *x, int *y)
{
    *x = 1;
    *y = 2;
}

void bar(void)
{
    int a, b;

    foo(&a, &b);

    printf("a: %d, b: %d\n", a, b); // prints a: 1, b: 2
}

Another option is to create a struct and return that struct:

struct answer {
    int x;
    int y;
};

struct answer foo(void)
{
    struct answer a;
    a.x = 1;
    a.y = -4;

    return a;
}

void bar(void)
{
    struct answer p = foo();

    printf("p.x: %d, p.y: %d\n", p.x, p.y);
}
user2736738
  • 30,591
  • 5
  • 42
  • 56
Pablo
  • 13,271
  • 4
  • 39
  • 59
3

Yes, you can do this with structures, which may contain arbitrary data fields, as with the following complete program:

#include <stdio.h>

struct tPair {int one; int two;};

struct tPair returnPair(void) {
    struct tPair plugh;
    plugh.one = 7;
    plugh.two = 42;
    return plugh;
}

int main(void) {
    struct tPair xyzzy = returnPair();
    printf("Pair is %d, %d\n", xyzzy.one, xyzzy.two);
    return 0;
}

If you compile and run that, you'll see:

Pair is 7, 42
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
2

You have to use struct, and at the same time I will suggest you get a book

#include <stdio.h>

struct Return_Value {
  int x;
  char *y;
};

typedef struct Return_Value Return_Value_t;


Return_Value_t r() {
  Return_Value_t revals = { .x = 1, .y = "hello" };
  return revals;
}


int main() {
  int x;
  char y[100];
  Return_Value_t reval = r();
  printf("%d\n", reval.x);
  printf("%s\n", reval.y);
}
user2736738
  • 30,591
  • 5
  • 42
  • 56
0.sh
  • 2,659
  • 16
  • 37