The World’s Shortest C Program

Every now and then it is fun to look at a very basic and fundamental example.  Every programmer is familiar with the “Hello World” program as a first program for a new board or programming language; However, ironically this is not the shortest program in C.  The shortest C program that can be written looks something like the following:

 

int main(void)

{

return 0;

}

 

This looks simple enough but could something even shorter be written?  Could the following be the shortest program?

 

void main(void)

{

}

 

Every C compiler that I’ve compiled these two programs in have resulted in a warning when main is defined as

 

void main(void)

 

The reason for this is that the C standards (I’ve examined C90 and C99) allow for two different definitions of main as

 

int main(void) {/* … */}

 

or

 

int main(int argc, char *argv[]) { /* … */ }

 

For embedded software there is not really much point in using the second definition.  In general, it would allow a host operating system to pass data to the program such as it’s name, etc.  Good coding practice would dictate that the program be written without errors so main should return an int as shown in the first example.

 

This leaves only the simple return statement.  Can the return statement be removed?  The C90 standard does not allow for the return statement to be removed.  The compiler will once again generate a warning.  However, the C99 standard does allow for the return statement to be implicitly declared (not included).  In C99 if no return statement is provided and main finishes (probably something we don’t want in an embedded system) then main will return 0 by default.

 

Once again the good practice would be to explicitly declare the return.  Most code bases include an explicit return 0 which is allowed by the standard.  The standard though also declares a value EXIT_SUCCESS or EXIT_FAILURE in stdlib.h .  It may be more appropriate to use these values than using a magic number of 0 or some other constant.  Returning anything else is a non-standard implementation.

Share >

2 thoughts on “The World’s Shortest C Program

  1. Not especially useful but every C compiler I’ve tested will compile and link a zero byte ‘.c’ file into a valid executable which, when run, prints out its own source code (ie nothing).

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.