The iconic “Hello, World” program simply prints the message “Hello, World” on the screen. Brian Kernighan used it as a very simple C example program in late 70’s. It became popular since then. Many use this as a first program to learn a new programming language. It is also used check the readiness of a development environment – whether the IDE, the compiler, the run-time environment etc. are all in place.
The “Hello, World” Program
#include <stdio.h>
main() {
printf("Hello, World\n");
}
Output:
$ cc test.c -o test
$ ./test
Hello, World
Recent C compilers don’t support the main() function without a return type. If we don’t specify, then the return type is assumed to an integer. This is a small variation of the same “Hello, World” program.
#include <stdio.h>
int main() {
printf("Hello, World\n");
return 0;
}
The “Hello, World” program is often used by the programmer to understand the basic build blocks of a programming language. This program varies significantly from language to language though. For many scripting languages, it is just a single line – and for others it’s a set of instructions.
“Hello, World” Program Components
Let’s have a look at the various parts of this C “Hello, World” Program.
The program starts with an include directive. It is a preprocessor to include the content of another file. Here we included “stdio.h” header file where all the standard input/output related function declarations are available. The used printf() is one such function.
The next few lines defined the function main(). The main() function is considered as the entry point of a C program. A C program can have many functions but the execution always starts from the main(). Unless we use some trick to execute other functions before main().
The function starts with a return type stating that the function will return an integer. Then comes the name of the function with a open brace to signify the start of a function.
The first statement is the printf() function call to print a message provided to the function. Here we provided the “Hello, World” string to print.
Next is a return statement to return the status of the program. Generally for successful execution, main() returns 0, otherwise a no-zero value to signify the failure code.
You might wonder who will catch the return value from the main(). Various execution environments start an executable and make use of the return value from main(). For example, in Linux systemd can start a Linux daemon by calling an executable. And can take action based on the return value – like if the executable returns a no-zero value, restart the program after some time.
And finally the program ends with a closing brace to signify the end of the main() function.
The post C “Hello, World” Program appeared first on QnA Plus.