How does ((a++,b)) work?

379 views Asked by At

In the above block of code, I am trying to understand how the line return reverse((i++, i)) is working.

#include <stdio.h>
        void reverse(int i);
        int main()
        {
            reverse(1);
        }
        void reverse(int i)
        {
            if (i > 5)
                return ;
            printf("%d ", i);
    //        return reverse(i++); -- stack overflow
            return reverse((i++, i));
        }

I also found the below piece of code which works similarly.

#include <stdio.h>
    int main()
    {
        int y = 1, x = 0;
        int l = (y++, x++) ? y : x;
        printf("%d\n", l);
    }

I am sorry if the question is very basic one. I felt it very difficult to understand. If someone can explain, it will be helpful.

1

There are 1 answers

3
Sourav Ghosh On BEST ANSWER

In your first code,

  • Case 1:

    return reverse(i++);
    

    will cause stack overflow as the value of unchanged i will be used as the function argument (as the effect of post increment will be sequenced after the function call), and then i will be increased. So, it is basically calling the reverse() with unchanged argument and will cause infinite recursion.

  • Case 2:

    OTOH,

    return reverse((i++, i));
    

    is the magic of comma operator, which basically evaluates the left expression, discards the value and finally returns (i.e., the result of using the comma operator) the type and value of the evaluation of the right hand side expression. So, the updated value of i will be used as function argument.

    It is equivalent to writing

    return reverse(++i);    //pre-inrement
    

    where the updated value of i will be used.


In your second code,

  int l = (y++, x++) ? y : x;

gets evaluated in the below order

  • y++ evaluated, result ignored. y is incremented.
  • x++ evaluated, result considered for ternary operator. It is FALSE. (Remember, post increment). Then, x is increased (post-increment).
  • As per the rule of the ternary operator, if the first operand (expression) is FALSE (evaluates to 0), then the third (operand) expression will get evaluated and the value will be returned.
  • It returns the incremented value of x to be stored in l, which is 1.