简体   繁体   中英

How to return three numbers in a function without using array or pointer in C?

The question:

Write a program that accepts three integers and then prints them in the order read and reversed. Use three functions, one to read the data, one to print them in the order read and one to print in reverse order.

The program (not finished):

#include <stdio.h>

int accept(){
    int x, y, z;
    printf("Please enter three integers: \n");
    scanf("%d %d %d", &x, &y, &z);
    return x, y, z;
}

int main(){
    x, y, z = accept();
}

Errors: error: 'x' undeclared (first use in this function)| note: each undeclared identifier is reported only once for each function it appears in| error: 'y' undeclared (first use in this function)| error: 'z' undeclared (first use in this function)|

How can I modify this program so that I can return the three variables without using arrays or pointers? Or is it impossible without using those?

You could create a struct that contains those three values

typedef struct MyStruct
{
    int a, b, c;
} MyStruct;

Then pass a pointer to the struct instance to and from the function (side note: ALWAYS do this with a pointer as it is more efficient because it only passes an 8 byte value. Passing the struct itself means (if I remember correctly) the compiler will attempt to split the struct into it's values when passing it as an argument)

Expansion of my comment. This is not sensible code and not recommended in practice but it is one way to amend your code to implement the requirement of multiple return values without arrays or pointers (or structs).

#include <stdio.h>

int accept(char opt){
    /* static variables remember their values between calls */
    static int x, y, z;

    if (opt=='x') return x;
    if (opt=='y') return y;
    if (opt=='z') return z;

    /* any other value of opt, read in new values */
    printf("Please enter three integers: \n");
    return scanf("%d %d %d", &x, &y, &z);
}

int main(){
    int x, y, z;
    accept(' ');
    x = accept('x');
    y = accept('y');
    z = accept('z');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM