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
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
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);
}
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
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);
}