FANDOM


Hello World, your first C program Edit

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

Code Edit

#include <stdio.h>

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

  return 0;
}

Explanation Edit

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 Edit

Hello, World!

Reading User Input Edit

Code Edit

#include <stdio.h>

int main()
{
  char input[20];

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

  return 0;
}

Explanation Edit

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 Edit

pie
You typed "pie"!

Ad blocker interference detected!


Wikia is a free-to-use site that makes money from advertising. We have a modified experience for viewers using ad blockers

Wikia is not accessible if you’ve made further modifications. Remove the custom ad blocker rule(s) and the page will load as expected.