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))

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:

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 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))

and the output is:

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.........