1

So in my professor's slides he simply gives examples like:

main()
{...
}

Right? But when I put this in visual studio it gives an error and it works when I put int in front of main. Why would my professor not put int in front of main? Can main be any other type of variable? Also I see a lot of int main(void). Why is this necessary? Can anything else be put in as a parameter?

windydys
  • 9
  • 7
  • 2
    Your professor is wrong. (or is simplifying the code to fit on a slide) – SLaks Apr 21 '13 at 21:50
  • 3
    Because your professor is writing code as if it were 1988. Even then it was a poor idea. As to your issue, you're using a C++ compiler, not C. VS only supports C89, VC++ rejects that code as C++ does not support implicit int. – Ed S. Apr 21 '13 at 21:52
  • 2
    Your professor is incompetent; you should report him or her. – Jim Balter Apr 21 '13 at 22:08
  • This is a valid declaration in C, not C++. – Thibaut Apr 21 '13 at 22:14
  • I realized he reuses slides that he made in 2004 without updating them. So that answers that – windydys Apr 21 '13 at 22:19

3 Answers3

6

main returns int. In older versions of C you could leave out the int and the compiler would pretend that you had said int. In C++, if 'main' doesn't explicitly return a value, it magically returns 0. You can return three values from main: 0, EXIT_SUCCESS, and EXIT_FAILURE. 0 is equivalent to EXIT_SUCCESS. The two named values are defined in <stdlib.h> and if you're coding in C++ in <cstdlib>.

The void is a C-style declaration that a function takes no arguments. In C++ you don't need it; a function that has no arguments in its declaration takes no arguments.

In general, though, main takes two arguments:

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

Those are the command-line arguments. argc is the number of arguments, and argv is an array of pointers to C-style strings that hold the arguments. The first string (argv[0]) is the name of the program.

Pete Becker
  • 74,985
  • 8
  • 76
  • 165
2

Because you are using either: C++ or C99 or C11.

C89 had an implicit int rule that mades main() equivalent to int main(). This does not exist in C++ and no longer exists since C99.

As you mentioned you are using Visual Studio and it does not support C99 and C11, you are probably compiling your program with the C++ compiler and not the C compiler.

ouah
  • 142,963
  • 15
  • 272
  • 331
1

The standard form of the main function, traditionally, is

int main(int argc, char **argv)

The int in the front means the main function returns an int, which is the exit code of main. The perimeter passed in by the operating system argc and argv are related to command-line arguments. argc is an int indicating the number of arguments passed in to the program, including the name of the program. And argv is pointed to the individual arguments. You can use argv[index] to access them. There are several handy libraries for parsing arguments, such as getopt.

lllluuukke
  • 1,304
  • 2
  • 13
  • 17