Programmer's Wiki
Advertisement

Hello World, your first C program[]

This is the traditional "Hello, World" program written in ANSI C.

Code[]

#include <stdio.h>

int main()
{
  printf("Hello, World!\n");

  return 0;
}

Explanation[]

Before a C program is compiled, it is fed to a preprocessor which looks for directives starting with #. This example program starts with a #include directive, telling the preprocessor to replace it with the specified header. A header contains function and variable declarations, type definitions and preprocessor macros. The stdio.h header contains declarations for some basic input/output functions.

The third line (int main()) starts the definition of a function called main. This function is called by the runtime library at program startup. The program will be terminated when we return from main. The int preceding the functions name indicates that main will return a value of type int.

The fifth line contain a call to the printf function, which is declared in stdio.h. In this case, the function will print what is in its first argument to stdout.

The return statement on the seventh line makes the main function return 0. The value returned from main is normally used as the exit value of the program, and a 0 normally means that there were no errors.

Output[]

Hello, World!

Reading User Input[]

Code[]

#include <stdio.h>

int main()
{
  char input[20];

  scanf("%s", input);
  printf("You typed \"%s\"!\n", input);

  return 0;
}

Explanation[]

In this example, we introduce the scanf function, which is used to read from stdin. The first argument to scanf is a format string, describing what we want to read. The %s indicates we want a string. The second argument is a pointer to a memory location where the string should be stored. We use the address of the input array. This is a dangerous approach, as scanf does not check if provided pointer points to a big enough memory area. If the user enters more than 19 characters, we have a buffer overflow, which can lead to a crached program or serious security issues.

fgets is a safer alternative, which allows us to specify the maximum number of characters to be read.

Output[]

pie
You typed "pie"!
Advertisement