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.
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.
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.
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.
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.
Letâs have a look at a typical C source file.
So letâs look at the main() function in a little more detail.
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
.
Geek Bits
You can compile and run your code on most machines using this trick:
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.
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.
The C language doesnât support strings out of the box.
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.
If you want to increase or decrease a variable, then you can
save space with the +=
and
-=
assignments.
Finally, if you want to increase or decrease a variable by 1, use ++ and --.
So far, every command youâve seen has fallen into one of the following two categories.
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.
Sometimes you group statements together to create block statements. Block statements are groups of commands surrounded by braces.
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.
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.
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?
The and operator ( &&
) evaluates to true, only if
both conditions given to it are
true.
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.
The or operator ( ||
) evaluates to true, if either condition given to it is true.
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.
! is the not operator. It reverses the value of a condition.
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.
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.
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:
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.
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?
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.
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:
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.
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:
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 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:
A break
statement will break
you straight out of the current loop, skipping whatever follows it in
the loop body. break
s 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
.
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:
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.
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.
Get Head First C now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.