Home > database >  Output is not what I had expected from the code
Output is not what I had expected from the code

Time:01-02

Please explain to me why this program is printing 12 12 as output, and not 7 7?

#include <stdio.h>
int addmult(int ii, int jj){
    int kk, ll;
    kk = ii   jj;
    ll = ii * jj;
    return(kk,ll);
}

int main(void) {
    int i = 3, j = 4, k, l;
    k = addmult(i,j);
    l = addmult(i,j);
    printf("\n%d\n%d",k,l);
}

CodePudding user response:

C does not allow the returning of multiple values from the same function. You could create a structure that holds the 2 values inside the function and return that, but a better approach would be to just call the function once each time.

CodePudding user response:

k,ll

is the comma operator. The C standard says:

The left operand of a comma operator is evaluated as a void expression; there is a sequence point between its evaluation and that of the right operand. Then the right operand is evaluated; the result has its type and value.

So

return(kk,ll);

is the same as

return ll;

and the code can be reduced to

int addmult(int ii, int jj){
    int ll;
    ll = ii * jj;
    return ll;
}

which makes it obvious that it will return 12 for both calls.

CodePudding user response:

As others have already answered above, The C language does not allow returning multiple values from a function (they are limited only to languages like Python).

Below is how you can achieve the purpose you wanted using struct in C

#include <stdio.h>

struct Pair {
    int x;
    int y;
};

struct Pair addmult(int ii, int jj){
    int kk, ll;
    kk = ii   jj;
    ll = ii * jj;

    struct Pair p = {kk, ll};
    return p;
}

int main(){

    int i = 3, j = 4, k, l;
    struct Pair p = addmult(i, j);
    k = p.x;
    l = p.y;
    printf("\n%d\n%d\n",k,l);

    return 0;
}
  •  Tags:  
  • c
  • Related