I would like to know Where arugment passed to main() gets stored in memory ,Do they simply get store in stack .If so then how k’s value is initialize in below code
#include<stdio.h>
int main(int k)
{
if(k<10)
printf("%d ",main(k+1));
return k;
}
O/p: 10 9 8 7 6 5 4 3 2
It’ll typically be stored wherever parameters to other functions get stored — which might be stack, register, or somewhere else entirely. Just for a few examples: on a SPARC, it’ll almost certainly be a register; on an x86 (in 32-bit mode) it’ll typically be the stack; on an IBM mainframe, it’ll normally be in a stack frame that’s dynamically allocated from the heap and linked together into a linked list that’s constructed/destroyed FIFO fashion.
Also note that it can/does vary even on a single machine with a single compiler — e.g., Microsoft VC++ can pass it on the stack or in a register depending on what compiler flag(s) you use. When/if you pass it in a register, it’ll (probably) be pushed on the stack inside the function anyway (to allow the recursion).
As an aside, I’ll also note that while
your codecallingmainis perfectly legal C, you are not allowed to callmainin C++.Edit: As for the initial value, that first parameter is traditionally called
argc, and tells you how many arguments were passed on the command line. If you invoke it (as you apparently have) with no command line, it should normally start out as1(the one argument being the name of the program itself, traditionally passed asargv[0]). If, for example, you invoked the program something like:It would normally exit without printing anything, because on the first entry to
main, the parameter would be greater than 10 so the body of theifstatement would never execute.