Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C main vs Java main

Tags:

java

c

What is the difference between the C main function and the Java main function?

int main( int argc, const char* argv[] )

vs

public static void main(String [] args)

How do these main functions relate to each languages creation and what are the benefits or outcomes of each?

like image 751
some_id Avatar asked Dec 10 '10 01:12

some_id


2 Answers

They do the same thing -- they're both intended to be the entry point into your program.

The difference in the signatures is because Java supports arrays which 'know' what their length is, and C does not. That's why you need argc, which is the count of the number of arguments passed.

In C, you return a success or failure code to the shell by using the return keyword, along with an integral value. In Java, you do it by calling System.Exit(code) with a return code. Two different ways of doing the same thing.

This guy has quite the write-up on the topic!

like image 126
Dave Markle Avatar answered Oct 01 '22 22:10

Dave Markle


The entry point in C (the main function) is used by the linker in a C++ compiler toolchain to run when the executable is run when an executable target is specified (otherwise the function is ignored). This entry point is part of the executable specification, and is quite static. It relies on the machine code being at a particular, concrete memory address. Imagining it like this, we place the args array pointer and the args count on the stack in memory which is set up when the executable runs by the operating system, and then run the machine code. Additionally, the C function has an int return type which is used to return failure or success to the shell (typically EXIT_SUCCESS (usually 0) or EXIT_FAILURE).

The entry point in Java (the main method) is dynamic as Java itself is an interpreted JIT language and relies on the class with this method in being on the classpath, and specified when the 'java' command is executed. There's a bit of processing involved in finding where the main method resides in the bytecode, and then running the contents through the bytecode interpreter. The args array also goes onto the stack to be used by the method body, but there's more setting up to it than that, since it's an array object -- we have it convert it after kickstarting through JNI or such. Java has no return type in the main method, but an unchecked exception can be thrown to indicate failure (perhaps).

like image 41
Chris Dennett Avatar answered Oct 01 '22 22:10

Chris Dennett