Wednesday, 8 October 2014

Argument to main function in C/C++

Q. What is the use of passing argument to main function?
Ans.
      First of all we can define main function in three different format in c/c++.
      int main(int argc,char * argv[]);
      int main(void);
      int main();

Instead of int return type we can have any other pre defined data type as return type of main function.

We start with the first prototype, here main function excepts two arguments one is of type int and other is of type array of pointers. First of all these arguments are used for passing the input together when we start executing the program. We don't have to pass the first argument it automatically counts how many argument we have passed while executing the program and that will be stored in argc.

Second argument argv[] is array of character pointers which stores the inputs which we have sent with execution. for ex. argv[0] will have first argument and argv[1] will have second argument .


In the second prototype it does not except any argument if we passes a argument the compiler will give an error.

Third one is similar to the second one but the difference is that in third one we can pass as many argument we want it will not give an error but in the second one it will give an error while we pass an argument to main function using terminal (linux users).

No comments:

Post a Comment

Related Posts

Related Posts Plugin for WordPress, Blogger...