C Language Getting started with C Language Original "Hello, World!" in K&R C

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

The following is the original "Hello, World!" program from the book The C Programming Language by Brian Kernighan and Dennis Ritchie (Ritchie was the original developer of the C programming language at Bell Labs), referred to as "K&R":

K&R
#include <stdio.h>

main()
{
    printf("hello, world\n");
}

Notice that the C programming language was not standardized at the time of writing the first edition of this book (1978), and that this program will probably not compile on most modern compilers unless they are instructed to accept C90 code.

This very first example in the K&R book is now considered poor quality, in part because it lacks an explicit return type for main() and in part because it lacks a return statement. The 2nd edition of the book was written for the old C89 standard. In C89, the type of main would default to int, but the K&R example does not return a defined value to the environment. In C99 and later standards, the return type is required, but it is safe to leave out the return statement of main (and only main), because of a special case introduced with C99 5.1.2.2.3 — it is equivalent to returning 0, which indicates success.

The recommended and most portable form of main for hosted systems is int main (void) when the program does not use any command line arguments, or int main(int argc, char **argv) when the program does use the command line arguments.


C90 §5.1.2.2.3 Program termination

A return from the initial call to the main function is equivalent to calling the exit function with the value returned by the main function as its argument. If the main function executes a return that specifies no value, the termination status returned to the host environment is undefined.

C90 §6.6.6.4 The return statement

If a return statement without an expression is executed, and the value of the function call is used by the caller, the behavior is undefined. Reaching the } that terminates a function is equivalent to executing a return statement without an expression.

C99 §5.1.2.2.3 Program termination

If the return type of the main function is a type compatible with int, a return from the initial call to the main function is equivalent to calling the exit function with the value returned by the main function as its argument; reaching the } that terminates the main function returns a value of 0. If the return type is not compatible with int, the termination status returned to the host environment is unspecified.



Got any C Language Question?