View Single Post
  #13 (permalink)  
Old 02-08-2010, 10:40 AM
Philip Potter
Guest
 
Posts: n/a
Default Re: newbie question on understanding the main() function

On 08/02/2010 03:46, some wrote:
> Thanks to all who responded to my question.
>
> Richard Heathfield wrote:
>> some wrote:
>>> If i write main like the following ways. Which one will compile and
>>> why?
>>>
>>> 1. char * main();
>>> 2. char * main(int, char);
>>> 3. char * main(char);
>>>
>>> I guess only first will(but, all three will flag a warning from the
>>> compiler)

>>
>> They are all wrong, but the compiler is not required to diagnose any of
>> them. This is one of those cases where the compiler is allowed to expect
>> you to know what you're doing;

>
> How do I know which cases are such(where compiler will not flag an
> error, but actually
> legal so don't evoke an error message from compiler)? I realize cases
> where I am
> allocating/deallocating memory, doing pointer arithmetic, returning
> address of a local
> variable from a function are cases where compiler will not balk as
> they are legal, but are
> wrong?
>
> Which book should I read to know about such cases?


A good starting place would be to read through the comp.lang.c FAQ at
http://c-faq.com/. There's a lot of discussion of different types of
not-well-defined-but-not-necessarily-error-producing code there to get
you started; particularly the sections on expressions, pointers and
memory allocation, but elsewhere too.

However, while it is a good resource, it is not enough on its own; it
must be read *in addition* to a good textbook such as those recommended
by santosh.

Also, if you haven't done so already, you should find out how to turn on
your compiler's stricter error checking modes. You mentioned you were
using gcc, so try:

gcc -ansi -pedantic -Wall -Wextra -o<destination> <source>

-ansi turns off extensions which are not allowed by the Standard
-pedantic emits all diagnostics (warnings) required by the Standard
-Wall turns on lots more warnings
-Wextra turns on even more warnings [can use -W instead of -Wextra]

In this case, -Wall enables the -Wmain warning:
-Wmain
Warn if the type of main is suspicious. main should be a function
with external linkage, returning int, taking either zero arguments,
two, or three arguments of appropriate types. This warning is
enabled by -Wall.

[If you're interested, the three-argument main() mentioned is a
nonstandard extension which (I think) provides a pointer to a data
structure representing the environment. Rather than using this
extension, you can just use the (standard, porable) getenv() function
instead.]

Phil
Reply With Quote