Tip 4: Don't return zero from main

07 October 11. [link] PDF version

Part of a series of tips on POSIX and C. Start from the tip intro page, or get 21st Century C, the book based on this series.

level: Hello, world.
purpose: Eliminate a line of unnecessary code from every program

Much of the tip-a-day series will be about making your life with C more like your life with quick-and-dirty scripting languages. Toward the goal of having fewer lines of code, let's shave a line off of every program you write.

Your program must have a main function, and it has to be of return type int, so you must absolutely have

int main(){ ... }
in your program.

You would think that you therefore have to have a return statement that indicates what integer gets returned. However, the C standard knows how infrequently this is used, and lets you not bother: “...reaching the } that terminates the main function returns a value of 0.” (C standard §5.1.2.2.3) That is, if you don't write return 0; as the last line of your program, then it will be assumed.

Tip #1 showed you this version of hello.c, and you can now see how I got away with a main containing only one line of code:

#include <stdio.h>
int main(){ printf("Hello, world.\n"); }

A few tips from now, we'll have cut this down to only one line.

To do:
Go through your programs and delete this line; see if it makes any difference.


[Previous entry: "Tip 3: Use libraries (even when your sysadmin doesn't want you to)"]
[Next entry: "Tip 5: Initialize wherever the first use may be"]