Shree Wankhede
Shree Wankhede

Reputation: 85

The following c code gives output 1 2 3 4 5 . How the code is executed?

I am not getting that how the following code is executing and output is 1 2 3 4 5 . Specially that return statement in reverse function with (i++, i).

#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++, i));
}

Upvotes: 4

Views: 401

Answers (2)

Prashanthv
Prashanthv

Reputation: 109

As it was already rightly pointed out by Felix, it is using the comma operator. You can simply write reverse(i++) or reverse(++i) or reverse(i+1) that'll do!

Upvotes: -1

user2371524
user2371524

Reputation:

The expression (i++, i) uses the comma operator -> it first evaluates the left hand side and then the right hand side, the result is that of the right hand side. As this operator also introduces a sequence point, the result is well-defined: it's the value of i after incrementing it.

In this example, it's just needlessly confusing code because it has the exact same result as just writing reverse(++i); (or even reverse(i + 1); which would better match a functional/recursive approach).

Upvotes: 7

Related Questions