NO

Author Topic: What's the difference between 'main()' and 'int main(void)'  (Read 3938 times)

avocado

  • Guest
What's the difference between 'main()' and 'int main(void)'
« on: January 02, 2013, 08:47:03 PM »
Hello,

I have an old C book that starts most of its examples with main()

But, using Pelles C IDE, I need to change this line to int main(void)

1.  Why is this? 
2.  Is there a way to write codes as in the book, using main()?

Thanks.

CommonTater

  • Guest
Re: What's the difference between 'main()' and 'int main(void)'
« Reply #1 on: January 02, 2013, 08:57:18 PM »
Yes you do need to write int _cdecl main (void) or int _cdecl main (int argc, char* argv[])... It's the new standard.

Pretty much you are dealing with a compiler that's smart, by compiler standards, but still a flaming idiot by human standards.  So what you have to do is to learn to talk to it because you can be certain it ain't going to adapt to you.

Actually the correct minimum C program is this...
Code: [Select]
#include <stdio.h>

int _cdecl main (void)
  {

    puts("hello world!");

    return 0;
  }

The specification of int and the return value are expected by the operating system.  It's used to return error codes to the OS when exiting.

It's marked _cdecl because with x64 code the standard calling convention is _fastcall and main has to be _cdecl.

It's parameters explicitly state (void) to say "no parameters" whereas in C-99  () means "any number of parameters".


Don't forget... there's a lot of C documentation out there from before the standards and a lot of stuff has changed... Be ready to keep up.


 

Offline Bitbeisser

  • Global Moderator
  • Member
  • *****
  • Posts: 772
Re: What's the difference between 'main()' and 'int main(void)'
« Reply #2 on: January 02, 2013, 09:46:21 PM »
Hello,

I have an old C book that starts most of its examples with main()

But, using Pelles C IDE, I need to change this line to int main(void)

1.  Why is this? 
Because your book is so old (or the author so ignorant) that it uses the old (as in outdated since at least 1989, with the release of the first ANSI C standard, referred to as C89/C90) "K&R" syntax. (K&R here refers to the original C authors, Brian Kernighan and Dennis Ritchie (+2012))
Pelle's C is compliant with ANSI C (now C11), which fixed the old ambiguous syntax, and defaults to the ANSI C syntax.

Quote
2.  Is there a way to write codes as in the book, using main()?
Yes, but is is highly discouraged to do so. Rather learn what the difference is (and why that change was made) and get used to the ANSI syntax and you will have much less problems, on almost any compiler, right from the start...
Quote
Thanks.
You're welcome...  ;)

Ralf
« Last Edit: January 02, 2013, 11:07:38 PM by Bitbeisser »