简体   繁体   中英

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));
}

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).

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM