문제

#include <stdio.h>

int main(int k)
{
    if(k<10)
            printf("%d ",main(k+1));
    return k;
}

output is:

10 9 8 7 6 5 4 3 2

In arguments of main() function, its argc but how is it used here?

도움이 되었습니까?

해결책 2

you have used main function as a recursive function thus when you call it with argument 1 it will stack main function while k reach the value of 10, then it dequeue the stack and print values by reverse order. you pass ,2,3,..10 and after dequeue of stack it will print 10,9,..2

다른 팁

First your signature of main is what standard defines it. Your compiler should give warning:

[Warning] 'main' takes only zero or two arguments [-Wmain]  

C11: 5.1.2.2.1 Program startup:

The function called at program startup is named main. The implementation declares no prototype for this function. It shall be defined with a return type of int and with no parameters:

int main(void) { /* ... */ }

or with two parameters (referred to here as argc and argv, though any names may be used1,as they are local to the function in which they are declared):

int main(int argc, char *argv[]) { /* ... */ }

or equivalent;10) or in some other implementation-defined manner.

Now, you can give any name to argcand argv. Here argc is k. Since you are passing no parameter to main the value of k is 1 because here argv[0] is the name of the program. Now k=1 is used by the program as initial value and the value

10 9 8 7 6 5 4 3 2 

is printed by recursive call of main.


1. emphasis is mine.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top