C Programming - Command Line Arguments - Discussion

Discussion Forum : Command Line Arguments - Find Output of Program (Q.No. 5)
5.
What will be the output of the program
#include<stdio.h>
void fun(int);

int main(int argc)
{
    printf("%d ", argc);
    fun(argc);
    return 0;
}
void fun(int i)
{
    if(i!=4)
        main(++i);
}
1 2 3
1 2 3 4
2 3 4
1
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
28 comments Page 2 of 3.

Ashok said:   10 years ago
But void function can't be to return any values how is this work?

Learner said:   1 decade ago
How are we taking the initial value of argc as 1? Since we don't know what arguments have been passed through cmd. Thanks in advance :').

Lokesh C P said:   1 decade ago
Its a recursive function, i++ means increment after the execution of the current statement, in this program value 1 is passed as argument value to main program again, program part below the recursive function call pushed to stack and because of I is post incremented main function calls infinite times, when stack is full it shows the stack overflow.

Jasneet said:   1 decade ago
If we replace "++i" with "i++"..then it shows stack overflow.

Can any one explain why ?

Shalini said:   1 decade ago
After printing 1 2 3 main again calls function.

It checks if(3!=4) //condition true.

So it calls main(++i) i.e main(4).

So 1 2 3 4 prints next time condition falls so program ends.

Deepak said:   1 decade ago
But it is printing 4 since in the 4th argument loop will be terminated. Then how 4 is printed?

Praveen said:   1 decade ago
Here only one argument is given. i.e. name of program. So. It takes only one argument by default. If you supply more arguments through command line output varies.

Rishi said:   1 decade ago
Why only argc as 1? I can always take 2 or 3, then the answer will vary right.

Anil kumar said:   1 decade ago
Thanks sreepal.

Merlin said:   1 decade ago
Thanks sreepal, your explanation is easy to understand.


Post your comments here:

Your comments will be displayed after verification.