开发者

main() function argument storage?

I would like to know Where arugment passed to main() gets stored in memory ,Do they simp开发者_如何学Pythonly 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 codecalling main is perfectly legal C, you are not allowed to call main in 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 as 1 (the one argument being the name of the program itself, traditionally passed as argv[0]). If, for example, you invoked the program something like:

prog a b c d e f g h i j k l m

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 the if statement would never execute.


parameters to main() are like arguments to any other method. They are part of the stack (depending on the processor, that could be in memory, or in a CPU register). In this case, when you call main(k+1), the result of k+1 is put on the stack before the recursive call is performed.

Note that the behavior of this is undefined since calling main() from within a C program is unspecified.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜