About main() and Advanced Warnings

The main() function is … a function and as such it is expected to either have a return value of a declared type (int, char …) or no return value at all in which case it should be declared using the keyword void. But from all the examples in the book you will notice that I do not use either of the two options. This is because, as part of my personal programming style, I like to use a “shortcut” that is part of the C language since the beginning of times (K&R). In fact, by default, declaring the main() function without specifying a type, I am telling the C compiler to assume it will be int.

Further, since we are not using an operating system, it does not matter if the main() function ever returns any value and therefore, in all the examples, you will notice that there is no return statement at the end of main() (by the way, we never return at all, as we typically stay in the main loop forever…

This is all nice and dandy, and can go completely unnoticed, until you enable the “advanced warnings” in the project configuration dialog box (Projects>Build Options for project”).

Project Build Options Dialog box

Enabling the Advanced Warnings is, in principle, a very good idea (and is now a default setting when you create a new project with MPLAB) since you can potentially expose a larger number of errors in your code, but it also creates a large number of “false alarms” as most of the “default” behaviors of the C compiler are now seen with a more critical eye…

So, if the advanced warnings are enabled, you will get a couple of extra error warnings:

  1. The compiler will demand that you give main() a type
  2. Depending if you choose to comply and declare main as
    a) int main( void)
    { …
    }
    or
    b) void main( void)
    { …
    }
    you are bound to get more warnings

If you chose option a), you will be asked to provide at least one return statement within the main function…

If you chose option b), you will receive another warning reminding you that main() was truly meant to return an integer …

In other words, you cannot win, because even if you chose a) and then add a useless return statement at the end of the main() function, you will be reminded later that the code is “unreachable” … which is profoundly true, since the application will typically remain in the main loop … forever.

My recommendation?

  1. Decide what is going to work best for your programming style.
  2. Tolerate the warnings, they are just that: warnings! They are not going to prevent your program from running correctly and they do not mean that there is necessarily anything wrong with your code,
  3. (and/or) Disable the advanced warnings immediately or just once you have convinced yourself that there is nothing ELSE wrong with your code.

The experts among you will learn/know how to disable individual warnings and will bypass all of the above…

This entry was posted in PIC24, Tips and Tricks. Bookmark the permalink.