rahul_T_T
rahul_T_T

Reputation: 133

Passing two values with parentheses in a single argument function

I got this question from a website asking to give the output of the code

void reverse(int i)
{
    if (i > 5)
        return ;
    printf("%d ", i);
    return reverse((i++, i));
}
int main(int argc, char *argv[]) {
    reverse(1);
    return 0;
}

Output is 1 2 3 4 5

but reverse function is called recursively passing two values within parantheses. How precedence and associativity working here?

Upvotes: 3

Views: 168

Answers (4)

user5697768
user5697768

Reputation:

Explaination:

void reverse(int i)
{
    if (i > 5)
       return ;
    printf("%d ", i);
    return reverse((i++, i)); // it's single arument that is (i++ , i)
 }
 int main(int argc, char *argv[]) {
    reverse(1);
    return 0;
 }

More explaination like

a = (1, 2, 3);

(1,2,3) is a single argument but what is assigned to a?

brackets are used so comma operator is executed first and we get the a assigned as 3 so statements before comma's are executed first and 3 is assigned

In your case
i++ is executed first and then i is passed as argument

Upvotes: 1

msc
msc

Reputation: 34588

According to haccks, here is a comma operator.

The expression:

(i++,  i)

First expression1 is evaluated, then expression2 is evaluated, and the value of expression2 is returned for the whole expression.

Upvotes: 3

Freek Wiedijk
Freek Wiedijk

Reputation: 511

This is not two values with extra parentheses, but one argument that contains a comma operator.

Upvotes: 4

haccks
haccks

Reputation: 106012

, in (i++, i) is a comma operator. It's operands evaluate from left to right. It evaluates i++, value of i get incremented and the value of the expression i++ is discarded and then the incremented value is passed to the function. So, ultimately only a single argument is passed to the function reverse.

Upvotes: 5

Related Questions