Learning C With Game Concepts/Introduction

From Wikibooks, open books for an open world
Jump to navigation Jump to search
This book attempts to introduce the C Language to new users while making the learning process interesting and giving them code to play with and modify as they continue educating themselves. The author of this book is a novice C programmer, writing for beginners, so I may not always use the best practice. Users who are interested in a more indepth understanding of the C language are recommended to check out the excellent C_Programming Wikibook.

Code Disclaimer[edit | edit source]

I'm new to sharing code with others, so I feel I should state that the code included in this Wikibook is generated by the author and any resemblance to code out in the wild is not intentional unless it is something basic like the implementation of a data structure (linked list, heap, etc).

Work Environment[edit | edit source]

This book recommends beginners use a Linux distribution, such as Linux Mint or Ubuntu. Although I'm unfamiliar with C programming on Windows, Microsoft's Visual C++ compiler should be able to compile C code, if it is available to you. The C language is easy to start learning in the Unix/Linux environment because the Gnu C Compiler (GCC) is included by default on most distributions. GCC is a command line utility that transforms C source code into machine instructions (binary). For writing your code, you'll need a Text Editor or Integrated Development Environment (IDE). An easy to use IDE is Geany, which you can find using your package manager on Linux.

Text Editors can be as basic as notepad or as complex as Vim and Emacs.

A Basic Program[edit | edit source]

Let's cover variables and standard IO in one fell swoop.


#include <stdio.h>

int main() {
    char input[50];   // # of characters we can read from standard input.
    char name[50];    // variable to contain a name

    printf("What is your name good sir?\n");
    fgets(input, sizeof(input), stdin);
    sscanf(input, "%s", &name);
    printf("Ah, %s, a pleasure to meet you.\n", name);

Before we compile this, let's review what our code does.

Header Files[edit | edit source]

The #include statement at the start of the program lets the compiler know that we want to use a library. Libraries in C are called Header files and end in the ".h" file extension. The C language contains standard libraries to perform all sorts of common tasks. STDIO, as the name implies, contains various functions for printing and reading.

Main Function / Statements[edit | edit source]

At the heart of every C program is the Main function. It contains the body of the program and is the first function called when the program is started. All functions follow this syntax:

datatype functionName (datatype argument) { 
   return (datatype);   // The datatype before the function name lets the 
                        // compiler know this is the kind of variable we will return.

A statement can be a variable declaration ( x = 100; ) or a function call ( CallingFunction(); ). All statements end with a semicolon and it is good practice to give every statement its own line. It's also important to check your code carefully to make sure you aren't missing any semicolons.

Data Types[edit | edit source]

There are 3 basic data types in C that we must use to declare our variables. We declare them using data types so the compiler knows exactly what each variable contains. They include:

  1. char (example 'a' | a single character)
  2. int (example 123 | a whole number)
  3. float (example 12.345 | a fractional number)

In our example we use char, but add brackets and a number after it. The syntax Variable[#] lets the compiler know that instead of a single character, we want an Array (string of characters).

Input/Output[edit | edit source]

We are using 3 functions from STDIO: printf, fgets, and sscanf. Our stdin and stdout comes from the command line where we will run the code.

Printf prints a string (as denoted by quotation marks) to standard output. If placeholders are present in the string (%letter) it will also print variables. Fgets reads in a line from standard input and puts it in our variable called Input. Sscanf looks at our variable called input and transfers it over to the variable called name. We'll want to use Input again when we get user input, so we can't leave our information in there or we'll overwrite it!

Returns[edit | edit source]

Return statements can return 1 datatype or variable from a function. The simplest example of why we use returns is to see if something is true or false. If you have a function called isCapital and call it on a letter, for example, isCapital('a') we would return(False). If we called isCapital('B'), we'd have our function return(True). The function that called the isCapital function would be designed to make a decision based on the value we returned.

Functions don't need to return a value though. Sometimes you may see 'void' used before a function. This means that the function doesn't return a datatype at all.

Compilation[edit | edit source]

Now that we've covered what our code does, let's compile and run it. Navigate to the folder that your C program is contained in. If you are unfamiliar with BASH, you'll need to learn about the cd and ls commands. From the command terminal type:

gcc intro.c -o intro

This command calls the compiler (GCC) to compile Intro.c and output an executable called Intro. If for some reason your file is not set as an executable after compilation, you can type:

chmod +x intro

To run your executable, type:


That wasn't as simple as printing "Hello World" but hopefully it wasn't too difficult to follow. As you continue reading, things should start to make more sense as you begin recognizing common patterns in programming.

Experiment #1[edit | edit source]

Before we move on, take a moment to tweak our Intro program. Declare an int variable called age. Change the first print statement to ask your age and use the integer placeholder %d to print your age in the second print statement.

A Modular Lifestyle[edit | edit source]

It would be very difficult to read large programs if we kept all of our functions and variables in one file. Suppose also, that we create a great function and want to use it in all of our programs, how would we do that?

If we want our reusable function to do what our last program did, we just take all the statements from before, put them in a function with a unique name, and place them in a header file.


#include <stdio.h>

int Greet() {
    char input[50];   // # of characters we can read from standard input.
    char name[50];    // variable to contain a name

    printf("What is your name good sir?\n");
    fgets(input, sizeof(input), stdin);
    sscanf(input, "%s", &name);
    printf("Ah, %s, a pleasure to meet you.\n", name);

Greet.h can now be included in our program like STDIO, and we don't even need to compile it before using it. The only difference is that instead of sharp brackets <> we use quotes "". If your main program and your header file are in the same folder, #include "Greet.h" is all you need to specify. If they are in different folders, you'll need to provide the fullpath for the compiler #include "fullpath/Greet.h"


#include "greet.h"

int main() {
   Greet();    // We declared this function in greet.h

When main_prog.c is compiled, the compiler looks for the header files and includes them in the compilation.

gcc main_prog.c -o main_prog

main_prog, the executable, will contain the machine instructions for the main program and the Greet file.

What is your name good sir?
Theodore Roosevelt
Ah, Theodore Roosevelt, a pleasure to meet you.