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

I don’t understand how the following code is executed and 1 2 3 4 5. is output. Specially, this return statement is in the inverse 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));
}
+4
source share
2 answers

The expression (i++, i)uses the comma operator → it first evaluates the left side, and then the right side, the result is on the right side. Since this operator also enters a sequence point, the result is correctly defined: this value iafter increasing it.

In this example, it just uselessly confuses the code because it has the same result as the record reverse(++i);(or even reverse(i + 1);that better matches the function-recursive approach).

+7

, . (i ++) (++ i) (i + 1), !

-1

Source: https://habr.com/ru/post/1687891/


All Articles