O'Reilly logo

Head First C by Dawn Griffiths, David Griffiths

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 1. Getting Started with C: Diving in

image with no caption

Want to get inside the computer’s head?

Need to write high-performance code for a new game? Program an Arduino? Or use that advanced third-party library in your iPhone app? If so, then C’s here to help. C works at a much lower level than most other languages, so understanding C gives you a much better idea of what’s really going on. C can even help you better understand other languages as well. So dive in and grab your compiler, and you’ll soon get started in no time.

C is a language for small, fast programs

The C language is designed to create small, fast programs. It’s lower-level than most other languages; that means it creates code that’s a lot closer to what machines really understand.

The way C works

Computers really only understand one language: machine code, a binary stream of 1s and 0s. You convert your C code into machine code with the aid of a compiler.

image with no caption
image with no caption
image with no caption

C is used where speed, space, and portability are important. Most operating systems are written in C. Most other computer languages are also written in C. And most game software is written in C.

Note

There are three C standards that you may stumble across. ANSI C is from the late 1980s and is used for the oldest code. A lot of things were fixed up in the C99 standard from 1999. And some cool new language features were added in the current standard, C11, released in 2011. The differences between the different versions aren’t huge, and we’ll point them out along the way.

But what does a complete C program look like?

To create a full program, you need to enter your code into a C source file. C source files can be created by any text editor, and their filenames usually end with .c.

Note

This is just a convention, but you should follow it.

Let’s have a look at a typical C source file.

image with no caption

So let’s look at the main() function in a little more detail.

Geek Bits

The printf() function is used to display formatted output. It replaces format characters with the values of variables, like this:

image with no caption

You can include as many parameters as you like when you call the printf() function, but make sure you have a matching % format character for each one.

Note

If you want to check the exit status of a program, type:

echo %ErrorLevel%

in Windows, or:

echo $?

in Linux or on the Mac.

But how do you run the program?

C is a compiled language. That means the computer will not interpret the code directly. Instead, you will need to convert—or compile—the human-readable source code into machine-readable machine code.

To compile the code, you need a program called a compiler. One of the most popular C compilers is the GNU Compiler Collection or gcc. gcc is available on a lot of operating systems, and it can compile lots of languages other than C. Best of all, it’s completely free.

Here’s how you can compile and run the program using gcc.

image with no caption

Geek Bits

You can compile and run your code on most machines using this trick:

image with no caption

This command will run the new program only if it compiles successfully. If there’s a problem with the compile, it will skip running the program and simply display the errors on the screen.

Do this!

You should create the cards.c file and compile it now. We’ll be working on it more and more as the chapter progresses.

The program works!

Congratulations! You have compiled and run a C program. The gcc compiler took the human-readable source code from cards.c and converted it into computer-readable machine code in the cards program. If you are using a Mac or Linux machine, the compiler will have created the machine code in a file called cards. But on Windows, all programs need to have a .exe extension, so the file will be called cards.exe.

image with no caption

The C language doesn’t support strings out of the box.

Note

But there are a number of C extension libraries that do give you strings.

C is more low-level than most other languages, so instead of strings, it normally uses something similar: an array of single characters. If you’ve programmed in other languages, you’ve probably met an array before. An array is just a list of things given a single name. So card_name is just a variable name you use to refer to the list of characters entered at the command prompt. You defined card_name to be a two-character array, so you can refer to the first and second character as char_name[0] and char_name[1]. To see how this works, let’s take a deeper dive into the computer’s memory and see how C handles text...

Painless Operations

Not all equals signs are equal.

In C, the equals sign ( =) is used for assignment. But a double equals sign ( ==) is used for testing equality.

image with no caption

If you want to increase or decrease a variable, then you can save space with the += and -= assignments.

image with no caption

Finally, if you want to increase or decrease a variable by 1, use ++ and --.

image with no caption

Two types of command

So far, every command you’ve seen has fallen into one of the following two categories.

Do something

Most of the commands in C are statements. Simple statements are actions; they do things and they tell us things. You’ve met statements that define variables, read input from the keyboard, or display data to the screen.

image with no caption

Sometimes you group statements together to create block statements. Block statements are groups of commands surrounded by braces.

image with no caption

Do something only if something is true

Control statements such as if check a condition before running the code:

image with no caption

if statements typically need to do more than one thing when a condition is true, so they are often used with block statements:

image with no caption

Here’s the code so far

/*
 * Program to evaluate face values.
 * Released under the Vegas Public License.
 * (c)2014 The College Blackjack Team.
 */
#include <stdio.h>
#include <stdlib.h>
int main()
{
    char card_name[3];
    puts("Enter the card_name: ");
    scanf("%2s", card_name);
    int val = 0;
    if (card_name[0] == 'K') {
        val = 10;
    } else if (card_name[0] == 'Q') {
        val = 10;
    } else if (card_name[0] == 'J') {
        val = 10;
    } else if (card_name[0] == 'A') {
        val = 11;
    } else {
        val = atoi(card_name);
    }
    printf("The card value is: %i\n", val);
    return 0;
}
image with no caption
image with no caption

Card counting? In C?

Card counting is a way to increase your chances of winning at blackjack. By keeping a running count as the cards are dealt, a player can work out the best time to place large bets and the best time to place small bets. Even though it’s a powerful technique, it’s really quite simple.

image with no caption

How difficult would this be to write in C? You’ve looked at how to make a single test, but the card-counting algorithm needs to check multiple conditions: you need to check that a number is >= 3 as well as checking that it’s <= 6.

You need a set of operations that will allow you to combine conditions together.

There’s more to booleans than equals...

So far, you’ve looked at if statements that check if a single condition is true, but what if you want to check several conditions? Or check if a single condition is not true?

&& checks if two conditions are true

The and operator ( &&) evaluates to true, only if both conditions given to it are true.

image with no caption

The and operator is efficient: if the first condition is false, then the computer won’t bother evaluating the second condition. It knows that if the first condition is false, then the whole condition must be false.

II checks if one of two conditions is true

The or operator ( ||) evaluates to true, if either condition given to it is true.

image with no caption

If the first condition is true, the computer won’t bother evaluating the second condition. It knows that if the first condition is true, the whole condition must be true.

! flips the value of a condition

! is the not operator. It reverses the value of a condition.

image with no caption

Geek Bits

In C, boolean values are represented by numbers. To C, the number 0 is the value for false. But what’s the value for true? Anything that is not equal to 0 is treated as true. So there is nothing wrong in writing C code like this:

int people_moshing = 34;
if (people_moshing)
    take_off_glasses();

In fact, C programs often use this as a shorthand way of checking if something is not 0.

The Polite Guide to Standards

The ANSI C standard has no value for true and false. C programs treat the value 0 as false, and any other value as true. The C99 standard does allow you to use the words true and false in your programs—but the compiler treats them as the values 1 and 0 anyway.

What’s the code like now?

int main()
{
    char card_name[3];
    puts("Enter the card_name: ");
    scanf("%2s", card_name);
    int val = 0;
    if (card_name[0] == 'K') {
        val = 10;
    } else if (card_name[0] == 'Q') {
        val = 10;
    } else if (card_name[0] == 'J') {
        val = 10;
    } else if (card_name[0] == 'A') {
        val = 11;
    } else {
        val = atoi(card_name);
    }
    /* Check if the value is 3 to 6 */
    if ((val > 2) && (val < 7))
        puts("Count has gone up");
    /* Otherwise check if the card was 10, J, Q, or K */
    else if (val == 10)
        puts("Count has gone down");
    return 0;
}
image with no caption

C programs often need to check the same value several times and then perform very similar pieces of code for each case.

Now, you can just use a sequence of if statements, and that will probably be just fine. But C gives you an alternative way of writing this kind of logic.

C can perform logical tests with the switch statement.

Pulling the ol’ switcheroo

Sometimes when you’re writing conditional logic, you need to check the value of the same variable over and over again. To prevent you from having to write lots and lots of if statements, the C language gives you another option: the switch statement.

The switch statement is kind of like an if statement, except it can test for multiple values of a single variable:

image with no caption

When the computer hits a switch statement, it checks the value it was given, and then looks for a matching case. When it finds one, it runs all of the code that follows it until it reaches a break statement. The computer keeps going until it is told to break out of the switch statement.

Watch it!

Missing breaks can make your code buggy.

Most C programs have a break at the end of each case section to make the code easier to understand, even at the cost of some efficiency.

Sometimes once is not enough...

You’ve learned a lot about the C language, but there are still some important things to learn. You’ve seen how to write programs for many different situations, but there is one fundamental thing that we haven’t really looked at yet. What if you want your program to do something again and again and again?

image with no caption

Using while loops in C

Loops are a special type of control statement. A control statement decides if a section of code will be run, but a loop statement decides how many times a piece of code will be run.

The most basic kind of loop in C is the while loop. A while loop runs code over and over and over as long as some condition remains true.

image with no caption

Do you do while?

There’s another form of the while loop that checks the loop condition after the loop body is run. That means the loop always executes at least once. It’s called the do...while loop:

do {
  
/* Buy lottery ticket */

} while(have_not_won);
image with no caption

Loops often follow the same structure...

You can use the while loop anytime you need to repeat a piece of code, but a lot of the time your loops will have the same kind of structure:

  • Do something simple before the loop, like set a counter.

  • Have a simple test condition on the loop.

  • Do something at the end of a loop, like update a counter.

For example, this is a while loop that counts from 1 to 10:

image with no caption

Loops like this have code that prepares variables for the loop, some sort of condition that is checked each time the loop runs, and finally some sort of code at the end of the loop that updates a counter or something similar.

...and the for loop makes this easy

Because this pattern is so common, the designers of C created the for loop to make it a little more concise. Here is that same piece of code written with a for loop:

image with no caption

for loops are actually used a lot in C—as much, if not more than, while loops. Not only do they make the code slightly shorter, but they’re also easier for other C programmers to read, because all of the code that controls the loop—the stuff that controls the value of the counter variable—is now contained in the for statement and is taken out of the loop body.

Every for loop needs to have something in the body.

You use break to break out...

You can create loops that check a condition at the beginning or end of the loop body. But what if you want to escape from the loop from somewhere in the middle? You could always restructure your code, but sometimes it’s just simpler skip out of the loop immediately using the break statement:

image with no caption

A break statement will break you straight out of the current loop, skipping whatever follows it in the loop body. breaks can be useful because they’re sometimes the simplest and best way to end a loop. But you might want to avoid using too many, because they can also make the code a little harder to read.

Watch it!

The break statement is used to break out of loops and also switch statements.

Make sure that you know what you’re break ing out of when you break.

...and continue to continue

If you want to skip the rest of the loop body and go back to the start of the loop, then the continue statement is your friend:

image with no caption

Tales from the Crypt

breaks don’t break if statements.

On January 15, 1990, AT&T’s long-distance telephone system crashed, and 60,000 people lost their phone service. The cause? A developer working on the C code used in the exchanges tried to use a break to break out of an if statement. But break s don’t break out of if s. Instead, the program skipped an entire section of code and introduced a bug that interrupted 70 million phone calls over nine hours.

The Polite Guide to Standards

The main() function has an int return type, so you should include a return statement when you get to the end. But if you leave the return statement out, the code will still compile—though you may get a warning from the compiler. A C99 compiler will insert a return statement for you if you forget. Use -std=c99 to compile to the C99 standard.

Your C Toolbox

You’ve got Chapter 1 under your belt, and now you’ve added C basics to your toolbox. For a complete list of tooltips in the book, see Appendix B.

image with no caption

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required