简体   繁体   中英

return function values as pointer

Question: Make function which will sum two integer variables (a,b) and then return result in variable rez , using pointer. Also, in the same function, return sum a+b+10 in another variable rez_a using pointer.

Well,here is the code. It returns only the first value(*p1)

#include <iostream>

using namespace std; 
int vrati(int a, int b) {
    int rez = a + b;
    int rez_a = a + b + 10;
    int* p1 = &rez;
    int* p2 = &rez_a;
    return *p1,*p2;
    

}
int main() {
    int a = 4;
    int b = 6;
    cout << vrati(a, b);
    
    return 0;
}

I think you are taking return too literally. I expect the function you are meant to write is this

void vrati(int a, int b, int *rez, int* rez_a) {
    *rez = a + b;
    *rez_a = a + b + 10;
}

int main() {
    int a = 4;
    int b = 6;
    int rez, rez_a;
    vrati(a, b, &rez, &rez_a);
    cout << rez << ' ' << rez_a;
    
    return 0;
}

This function returns values, but it doesn't use return . I can understand why you were confused.

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