C Programming - Functions - Discussion

Discussion Forum : Functions - Find Output of Program (Q.No. 12)
12.
What will be the output of the program?
#include<stdio.h>

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

int main()
{
    int i=3, j=4, k, l;
    k = addmult(i, j);
    l = addmult(i, j);
    printf("%d %d\n", k, l);
    return 0;
}
12 12
No error, No output
Error: Compile error
None of above
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
91 comments Page 5 of 10.

Ravindra bagale said:   1 decade ago
Keep one thing in mind, comma operator means, the rightmost value only.

Ex. Return (1, 2) = 2.

Ex. i = j+ (1, 4, 7, 9, 12) then expression is i = j+12.

That's it.

Viren said:   1 decade ago
I had run this program in visual studio and its showing compilation error. I don't think that its output is 12, 12. If you think so, than please give an explanation.

Achal said:   7 years ago
Well here the concept of comma operator is used!.

The rightmost value in the return statement will be taken into consideration. Hence, it will be 12 each time.

Kamrul Hasan said:   9 years ago
Comma (,) Operator has LEFT to RIGHT associativity rules, so if we assign/return a VARIABLE a list of values with comma then it takes the RIGHT most value.

Ankush said:   1 decade ago
@viren it also depends upon the type of compiler you are using, in gcc compiler it is running of < code blocks > as comma operator is working in it.

Prudhvi said:   1 decade ago
I read some where a function can return only one value at a time. So now according to the above pgm has two return values. How come it executes the code?

Tina said:   1 decade ago
I think the answer should be compile error. Because the function return two values at a time which is not possible.

Can anyone explain me the concept ?

Am12cs said:   1 decade ago
int i=3, j=4, k, l;
k = addmult(i, j);
l = addmult(i, j);

A function cannot return two values at a time, k and l.

Hence it an compiler error.

Akash said:   1 decade ago
Comma (,) operator has left to right associativity, so while returning the rightmost operator will be returned and no error because of this.

Sharenu said:   1 decade ago
Thank you @sundar. But how to differentiate comma and comma opertor. Where are the comma operators necessary. Can you please explain me.


Post your comments here:

Your comments will be displayed after verification.