简体   繁体   中英

What is the difference between main in C & C++

What is the difference between main in a C program and in a C++ program?

Other than

  1. return statement ( default 1 in C,`0 in C++)
  2. syntax:

     int main() { /* … */ } int main(int argc, char* argv[]) { /* … */ } int main() , void main() ,etc ... 

Mainly:

  1. difference between main in C Program & C++ program

  2. Are there any differences between C++98, C++03 and C++0x according to the ISO standard? ie program's entry point (program startup implementation), etc.

In modern C, and modern C++:

  • main is always either int main() or int main(int, char*[]) .
  • In C89, you have to return from main explicitly.
  • In C99 and C++, if you don't return explicitly, you implicitly return 0 .

[ (I've checked the C99 standard now and edited this paragraph.) ] For your second question, in C99 you must have precisely one of the two main functions. In C++ the standard says that a program is well-formed if it has a main function that returns int , and that every conforming implementation must accept the two listed versions as an entry point (for a "hosted program", eg not for the Linux kernel); see 3.6.1. [/edit] To the best of my knowledge, calling conventions are also not part of the standard.

I don't understand your question about memory, but do note that neither C99 nor C++03 have anything but a rudimentary memory model, whereas the new C++0x explicitly adds a memory model in order to enable well-defined concurrent and atomic operations.

In C, as opposed to C++, main can be called recursively.

/* valid C */
#include <stdio.h>
int main(int argc, char **argv) {
  putchar(argc ? '.' : '\n');
  if (argc == 0) return 0;
  return main(argc - 1, NULL);
}

C99 and C++ are put in line for the definition of main in hosted environments. There are two function interfaces that are allowed

int main(void);
int main(int, char*[]);

Both languages allow the implicit return from main without return statement in which case a return value of EXIT_SUCCESS is returned to the caller.

Edit: Is there any difference in program startup implementation is there any difference in c++98,C++03,C+++0x main ,etc.........

Not in main . However, there is a huge difference in what happens before main is called in C versus C++. In C++, objects with static storage are typically initialized prior to entering main .

Note:
An implementation is allowed to perform dynamic initializations of static data in the midst of main , but it must do so prior to the first reference to that static data. I've never run across an implementation that takes advantage of this flexibility.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM