Wednesday, February 23, 2011

A question on main.......

A few days back while playing with the programs i got stucked at the following program::

void (main(main))
{
printf("main=%d",++main);
}

that was the multiple choice question and there was an option compilation fails ,i smartly tick that and moved on to the next question ,but after doing all the question when i was checking my result i got 6/7 then i saw what went wrong because according to me the questions were simple....then i ran this on the machine instead of my mind and amazingly got that compiled without any error  and the output was:
main=2

I was amazed by seeing the answer,so started to find how it compiles,then i checked with other functions also and got the reason why void (main()) compiles without any error,but the solution of this question was the mystery again that is why void (main(main)) compiles....then i tried further to get the answer.......
after a little exploration i came up with the common misconception that main() does not accept any argument instead it can take any number of arguments.
then i take a lok at the standard for the main declaration and found this..
then i got why void (main(abc)),void main(main(abc,def,ghi,jkl)) or with any number arguments compiles under C89 because under C89 main() is acceptable and can take any number of arguments....
and i knew that main can be used as a variable name or identifier and is not treated as a keyword....so i come to know that  why void (main(main)) compiles??? because main can take any number of arguments under C89 and main can be used as a variable name or identifier ....

then again i stucked why the output is 2 that is why main equals to 1 ........then i tried the following code:

void (main(a,b,c,d))
{
printf("a=%d,b=%d,c=%d,d=%d",a,b,c,d);
}

and the output is:
a=1,b=garbage,c=garbage,d=garbage

Then i tried that on three different compilers that is turboc,dev and gcc on all the compilers it gives 1 for the first argument and garbage for the others the reason for this is still a mystery for me ....
anybody if knows why the first argument value is always 1 please post the reason as comment to this post.......and if you found this useful please rate this post.........

2 comments:

  1. by milan...
    so after looking at it again i got the answer why a is 1.when we run the prgm the number of command line arguments are what goes into the main function as the 1st argument..
    and program name is counted in the command line argument ,so by default 1st argument is 1 that is prgm name ...and
    suppose the exe is prgm.exe and we give the command as:
    prgm 2 3 4
    then the value of a is 4....

    ReplyDelete

Feel free to comment......