| stage | prewriting |
|---|
The following program is a basic Hello, World program where text is printed to
a screen.
#include <stdio.h>
int main(void) {
printf("Hello, World\n");
return 0;
}Going line by line:
#include <stdio.h>- this includes a standard IO header file from your system in your program, so theprintffunction works. In C programs there are many standard library header files used from the system and they come with the compiler, so you don't need to reinvent everything and you have best practices at your disposal.int main(void)- each C program starts with amain()function. Theintkeyword indicates thatmainreturns a value of integer type. Thevoidkeyword indicates that function doeesn't take any arguments.{and}- curly brackets wrap a block of code such asmainfunction.printf("Hello, World\n");- this prints textHello, Worldtext and a new line on your screen when program is compiled and run. The additional\nstands for a new line character.return 0;- themainfunction returns a value 0.
To be able to run your Hello, World program, you need to first compile it.
To compile a C program, you need to have a compiler. In above case we will use a
gcc compiler.
gcc hello.c -o hello.ogccis a command for running a compilerhello.cis a C source code file with above code-o hello.ois optional and defines a binary file that is created. If left out the output file will be automatically set by compiler. For example,a.out.
You can then run this C program by executing
./hello.oWhich prints in command line:
Hello, WorldYou can pass arguments to main():
#include <stdio.h>
int main(int argc, char **argv) {
printf("Hello, %s\n", argv[1]);
return 0;
}int main(...)- means that themain()function will return a value of integer type.int argc- first argument defines the number of arguments that will be passed to the compiled program.char **argv- the second argument defines an array of character strings.
Let's compile and run the program:
gcc hello.c -o hello.o
./hello.o "PHP"The output of above program will be:
Hello, PHP
In C there are two types of comments:
- Single line comments
#include <stdio.h>
// This is a single line comment.
int main(void) {
printf("Hello, World\n");
return 0;
}- Multi line comments
They are wrapped between /* and */:
#include <stdio.h>
/*
* This is a multi line comment.
*/
int main(void) {
printf("Hello, World\n");
return 0;
}Above has already been used the printf() function.