Notes

C and C++ main() methods

author: Paul Kim

categories: c, cpp

tags: c, cpp

There are 4 C language standards (aka versions) that I am aware of: C89, C90, C99, C11.

  • C89 - In 1989, the C standard was ratified as ANSI X3.159-1989 "Programming Language C". This version of the language is often referred to as ANSI C or Standard C, or sometimes C89.
  • C90 - In 1990, this ANSI C standard (with formatting changes) was adopted by the International Organizaion for Standardization (ISO) as ISO/IEC 0900:1990, which is sometimes called C90. Therefore, the terms "C89" and "C90" refer to the same programming language.
  • C99 - The C standard was further revised in the late 1990s, leading to the publication of ISO/IEC 9899:1999 in 1999, which is commonly referred to as C99.
  • C11 - In 2007, work began on another revision of the C standard, informally called "C1X" until its offical publication of ISO/IEC 9899:2011 on 2011-12-08, which is referred to as C11.

Here are the various ways in which you can define the main() method in C.

In C89/99, the return type int is not required.

main() {
  // do something
}

In C99 or C11, the return type int is required. Otherwise, you might get a warning: warning: type specifier missing, defaults to 'int' [-Wimplicit-int]

int main() {
  // do something

  return 0;
}

The main() method can have 0 arguments.

What is the difference between int main() and int main(void)? In C++, there is no difference. However, in C, the second definition is considered technically better as it clearly specifies that main can only be called without any parameter. Difference between “int main()” and “int main(void)” in C/C++?

int main() {
  // do something

  return 0;
}

// in C, this is technically better because it explicitly
// specifies that main can only be called without any parameter
int main(void) {
  // do something

  return 0;
}

The main() method can take arguments. argc is the # of arguments and argv is an array of strings representing the arguments passed to main.

int main(int argc, char* argv[]) {
  // do something

  return 0;
}

The arguments passed to main() method can also be written like this:

int main(int argc, char** argv) {
  // do something

  return 0;
}
Source

ChromeEdgeFirefoxOpera

© 2021 paulkode.com. All rights reserved.