To create a simple C program which prints “Hello, World” on the screen, use a text editor to create a new file (e.g.
hello.c — the file extension must be .c) containing the following source code:
Hello.c
#include <stdio.h>
int main(void)
{
puts("Hello, World");
return 0;
}
Let’s look at this simple program line by line
#include <stdio.h>
This line tells the compiler to include the contents of the standard library header file stdio.h in the program. Headers are usually files containing function declarations, macros and data types, and you must include the header file before you use them. This line includes stdio.h so it can call the function puts().
int main(void)
This line starts the definition of a function. It states the name of the function (main), the type and number of arguments it expects (void, meaning none), and the type of value that this function returns (int). Program execution starts in the main() function.
{
…
…
}
The curly braces are used in pairs to indicate where a block of code begins and ends. They can be used in a lot of ways, but in this case they indicate where the function begins and ends.
puts("Hello, World");
This line calls the puts() function to output text to standard output (the screen, by default), followed by a newline
The string to be output is included within the parentheses.
“Hello, World” is the string that will be written to the screen. In C, every string literal value must be inside the
double quotes “…”.
See more about strings.
In C programs, every statement needs to be terminated by a semi-colon (i.e. ;).
return 0;
When we defined main(), we declared it as a function returning an int, meaning it needs to return an integer. In
this example, we are returning the integer value 0, which is used to indicate that the program exited successfully.
After the return 0; statement, the execution process will terminate.
Hello World in K&R C
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”:
#include <stdio.h>
main()
{
printf("hello, world\n");
}