Showing posts with label function overriding. Show all posts
Showing posts with label function overriding. Show all posts

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

Two main function in java

Q. The question is that can we have two main functions in java?

Ans. Yes, We can have two main function in java but the function's prototype should be different.

 For example we can have two functions like-
public static void main(string[] args);

and second one may be

public static void main(int a);


The reason for this is that when compiler/interpreter starts executing it starts with finding a function whose prototype is similar to the first one i have written have which takes argument as a array of string objects. It does not consider the second main function because it has different argument then the one which is needed. So we can have two main functions with two different arguments and one of them should be similar to the first one.

Related Posts

Related Posts Plugin for WordPress, Blogger...