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.
In your first code,
Case 1:
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 theni
will be increased. So, it is basically calling thereverse()
with unchanged argument and will cause infinite recursion.Case 2:
OTOH,
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
where the updated value of
i
will be used.In your second code,
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).x
to be stored inl
, which is1
.